Date: (Fri) Jan 29, 2016

Introduction:

Data: Source: Training: https://www.kaggle.com/c/titanic/download/train.csv
New: https://www.kaggle.com/c/titanic/download/test.csv
Time period:

Synopsis:

Based on analysis utilizing <> techniques, :

Summary of key steps & error improvement stats:

Prediction Accuracy Enhancement Options:

  • transform.data chunk:
    • derive features from multiple features
  • manage.missing.data chunk:
    • Not fill missing vars
    • Fill missing numerics with a different algorithm
    • Fill missing chars with data based on clusters

[](.png)

Potential next steps include:

  • Organization:
    • Categorize by chunk
    • Priority criteria:
      1. Ease of change
      2. Impacts report
      3. Cleans innards
      4. Bug report
  • all chunks:
    • at chunk-end rm(!glb_)
  • manage.missing.data chunk:
    • cleaner way to manage re-splitting of training vs. new entity
  • extract.features chunk:
    • Add n-grams for glbFeatsText
      • “RTextTools”, “tau”, “RWeka”, and “textcat” packages
  • fit.models chunk:
    • Prediction accuracy scatter graph:
    • Add tiles (raw vs. PCA)
    • Use shiny for drop-down of “important” features
    • Use plot.ly for interactive plots ?

    • Change .fit suffix of model metrics to .mdl if it’s data independent (e.g. AIC, Adj.R.Squared - is it truly data independent ?, etc.)
    • create a custom model for rpart that has minbucket as a tuning parameter
    • varImp for randomForest crashes in caret version:6.0.41 -> submit bug report

  • Probability handling for multinomials vs. desired binomial outcome
  • ROCR currently supports only evaluation of binary classification tasks (version 1.0.7)
  • extensions toward multiclass classification are scheduled for the next release

  • fit.all.training chunk:
    • myplot_prediction_classification: displays ‘x’ instead of ‘+’ when there are no prediction errors
  • Compare glb_sel_mdl vs. glb_fin_mdl:
    • varImp
    • Prediction differences (shd be minimal ?)
  • Move glb_analytics_diag_plots to mydsutils.R: (+) Easier to debug (-) Too many glb vars used
  • Add print(ggplot.petrinet(glb_analytics_pn) + coord_flip()) at the end of every major chunk
  • Parameterize glb_analytics_pn
  • Move glb_impute_missing_data to mydsutils.R: (-) Too many glb vars used; glb_<>_df reassigned
  • Do non-glm methods handle interaction terms ?
  • f-score computation for classifiers should be summation across outcomes (not just the desired one ?)
  • Add accuracy computation to glb_dmy_mdl in predict.data.new chunk
  • Why does splitting fit.data.training.all chunk into separate chunks add an overhead of ~30 secs ? It’s not rbind b/c other chunks have lower elapsed time. Is it the number of plots ?
  • Incorporate code chunks in print_sessionInfo
  • Test against
    • projects in github.com/bdanalytics
    • lectures in jhu-datascience track

Analysis:

rm(list = ls())
set.seed(12345)
options(stringsAsFactors = FALSE)
source("~/Dropbox/datascience/R/myscript.R")
source("~/Dropbox/datascience/R/mydsutils.R")
## Loading required package: caret
## Loading required package: lattice
## Loading required package: ggplot2
source("~/Dropbox/datascience/R/myplot.R")
source("~/Dropbox/datascience/R/mypetrinet.R")
source("~/Dropbox/datascience/R/myplclust.R")
source("~/Dropbox/datascience/R/mytm.R")
# Gather all package requirements here
suppressPackageStartupMessages(require(doMC))
glbCores <- 6 # of cores on machine - 2
registerDoMC(glbCores) 

suppressPackageStartupMessages(require(caret))
require(plyr)
## Loading required package: plyr
require(dplyr)
## Loading required package: dplyr
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:plyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
require(knitr)
## Loading required package: knitr
#source("dbgcaret.R")
#packageVersion("snow")
#require(sos); findFn("cosine", maxPages=2, sortby="MaxScore")

# Analysis control global variables
# Inputs
#   url/name = "<pointer>"; if url specifies a zip file, name = "<filename>"
#   sep = choose from c(NULL, "\t")
glbObsTrnFile <- list(url = "https://www.kaggle.com/c/titanic/download/train.csv") 

glbObsNewFile <- list(url = "https://www.kaggle.com/c/titanic/download/test.csv") # default OR
    #list(splitSpecs = list(method = NULL #select from c(NULL, "condition", "sample", "copy")
    #                      ,nRatio = 0.3 # > 0 && < 1 if method == "sample" 
    #                      ,seed = 123 # any integer or glbObsTrnPartitionSeed if method == "sample" 
    #                      ,condition = # or 'is.na(<var>)'; '<var> <condition_operator> <value>'    
    #                      )
    #    )                   

glbInpMerge <- NULL #: default
#     list(fnames = c("<fname1>", "<fname2>")) # files will be concatenated

glb_is_separate_newobs_dataset <- TRUE    # or TRUE
    glb_split_entity_newobs_datasets <- TRUE  # FALSE not supported - use "copy" for glbObsNewFile$splitSpecs$method # select from c(FALSE, TRUE)

glbObsDropCondition <- NULL # : default
#   enclose in single-quotes b/c condition might include double qoutes
#       use | & ; NOT || &&    
#   '<condition>' 
    # 'grepl("^First Draft Video:", glbObsAll$Headline)'
    # '(is.na(glbObsAll[, glb_rsp_var_raw]) & grepl("Train", glbObsAll[, glbFeatsId]))'
#nrow(do.call("subset",list(glbObsAll, parse(text=paste0("!(", glbObsDropCondition, ")")))))
    
glb_obs_repartition_train_condition <- NULL # : default
#    "<condition>" 

glb_max_fitobs <- NULL # or any integer
glbObsTrnPartitionSeed <- 123 # or any integer
                         
glb_is_regression <- FALSE; glb_is_classification <- !glb_is_regression; 
    glb_is_binomial <- TRUE # or TRUE or FALSE

glb_rsp_var_raw <- "Survived"

# for classification, the response variable has to be a factor
glb_rsp_var <- "Survived.fctr"

# if the response factor is based on numbers/logicals e.g (0/1 OR TRUE/FALSE vs. "A"/"B"), 
#   or contains spaces (e.g. "Not in Labor Force")
#   caret predict(..., type="prob") crashes
glb_map_rsp_raw_to_var <- #NULL 
function(raw) {
#     return(raw ^ 0.5)
#     return(log(raw))
#     return(log(1 + raw))
#     return(log10(raw)) 
#     return(exp(-raw / 2))
    ret_vals <- rep_len(NA, length(raw)); ret_vals[!is.na(raw)] <- ifelse(raw[!is.na(raw)] == 1, "Y", "N"); return(relevel(as.factor(ret_vals), ref="N"))
#     as.factor(paste0("B", raw))
#     as.factor(gsub(" ", "\\.", raw))    
    }

#if glb_rsp_var_raw is numeric:
#print(summary(glbObsAll[, glb_rsp_var_raw]))
#glb_map_rsp_raw_to_var(tst <- c(NA, as.numeric(summary(glbObsAll[, glb_rsp_var_raw])))) 

#if glb_rsp_var_raw is character:
#print(table(glbObsAll[, glb_rsp_var_raw]))
#glb_map_rsp_raw_to_var(tst <- c(NA, names(table(glbObsAll[, glb_rsp_var_raw])))) 

glb_map_rsp_var_to_raw <- #NULL 
function(var) {
#     return(var ^ 2.0)
#     return(exp(var))
#     return(10 ^ var) 
#     return(-log(var) * 2)
    as.numeric(var) - 1
#     levels(var)[as.numeric(var)]
#     gsub("\\.", " ", levels(var)[as.numeric(var)])
#     c("<=50K", " >50K")[as.numeric(var)]
#     c(FALSE, TRUE)[as.numeric(var)]
}
#glb_map_rsp_var_to_raw(glb_map_rsp_raw_to_var(tst))

if ((glb_rsp_var != glb_rsp_var_raw) && is.null(glb_map_rsp_raw_to_var))
    stop("glb_map_rsp_raw_to_var function expected")

# List info gathered for various columns
# <col_name>:   <description>; <notes>
# survival        Survived
#                 (0 = No; 1 = Yes)
# pclass          Passenger Class
#                 (1 = 1st; 2 = 2nd; 3 = 3rd)
# name            Name
# sex             Sex
# age             Age
# sibsp           Number of Siblings/Spouses Aboard
# parch           Number of Parents/Children Aboard
# ticket          Ticket Number
# fare            Passenger Fare
# cabin           Cabin
# embarked        Port of Embarkation
#                 (C = Cherbourg; Q = Queenstown; S = Southampton)
# 
# SPECIAL NOTES:
# Pclass is a proxy for socio-economic status (SES)
#  1st ~ Upper; 2nd ~ Middle; 3rd ~ Lower
# 
# Age is in Years; Fractional if Age less than One (1)
#  If the Age is Estimated, it is in the form xx.5
# 
# With respect to the family relation variables (i.e. sibsp and parch)
# some relations were ignored.  The following are the definitions used
# for sibsp and parch.
# 
# Sibling:  Brother, Sister, Stepbrother, or Stepsister of Passenger Aboard Titanic
# Spouse:   Husband or Wife of Passenger Aboard Titanic (Mistresses and Fiances Ignored)
# Parent:   Mother or Father of Passenger Aboard Titanic
# Child:    Son, Daughter, Stepson, or Stepdaughter of Passenger Aboard Titanic
# 
# Other family relatives excluded from this study include cousins,
# nephews/nieces, aunts/uncles, and in-laws.  Some children travelled
# only with a nanny, therefore parch=0 for them.  As well, some
# travelled with very close friends or neighbors in a village, however,
# the definitions do not support such relations.

# currently does not handle more than 1 column; consider concatenating multiple columns
# If glbFeatsId == NULL, ".rownames <- as.numeric(row.names())" is the default
glbFeatsId <- "PassengerId" # choose from c(NULL : default, "<id_feat>") 
glbFeatsCategory <- "Pclass.fctr" # choose from c(NULL : default, "<category_feat>")

# User-specified exclusions
glbFeatsExclude <- c(NULL
#   Feats that shd be excluded due to known causation by prediction variable
# , "<feat1", "<feat2>"
#   Feats that are linear combinations (alias in glm)
#   Feature-engineering phase -> start by excluding all features except id & category & work each one in
    #,"Survived"
    #,"PassengerId"
    ,"Pclass"       # Derived Pclass.fctr
    ,"Name","Sex","Age","SibSp","Parch","Ticket","Fare","Cabin","Embarked"
                    ) 
if (glb_rsp_var_raw != glb_rsp_var)
    glbFeatsExclude <- union(glbFeatsExclude, glb_rsp_var_raw)                    

glbFeatsInteractionOnly <- list()
#glbFeatsInteractionOnly[["<child_feat>"]] <- "<parent_feat>"

glbFeatsDrop <- c(NULL
                # , "<feat1>", "<feat2>"
                )

glb_map_vars <- NULL # or c("<var1>", "<var2>")
glb_map_urls <- list();
# glb_map_urls[["<var1>"]] <- "<var1.url>"

glb_assign_pairs_lst <- NULL; 
# glb_assign_pairs_lst[["<var1>"]] <- list(from=c(NA),
#                                            to=c("NA.my"))
glb_assign_vars <- names(glb_assign_pairs_lst)

# Derived features; Use this mechanism to cleanse data ??? Cons: Data duplication ???
glbFeatsDerive <- list();

# glbFeatsDerive[["<feat.my.sfx>"]] <- list(
#     mapfn = function(<arg1>, <arg2>) { return(function(<arg1>, <arg2>)) } 
#   , args = c("<arg1>", "<arg2>"))
#myprint_df(data.frame(ImageId = mapfn(glbObsAll$.src, glbObsAll$.pos)))
#data.frame(ImageId = mapfn(glbObsAll$.src, glbObsAll$.pos))[7045:7055, ]

    # character
#     mapfn = function(Week) { return(substr(Week, 1, 10)) }

#     mapfn = function(descriptor) { return(plyr::revalue(descriptor, c(
#         "ABANDONED BUILDING"  = "OTHER",
#         "**"                  = "**"
#                                           ))) }

#     mapfn = function(description) { mod_raw <- description;
    # This is here because it does not work if it's in txt_map_filename
#         mod_raw <- gsub(paste0(c("\n", "\211", "\235", "\317", "\333"), collapse = "|"), " ", mod_raw)
    # Don't parse for "." because of ".com"; use customized gsub for that text
#         mod_raw <- gsub("(\\w)(!|\\*|,|-|/)(\\w)", "\\1\\2 \\3", mod_raw);
    # Some state acrnoyms need context for separation e.g. 
    #   LA/L.A. could either be "Louisiana" or "LosAngeles"
        # modRaw <- gsub("\\bL\\.A\\.( |,|')", "LosAngeles\\1", modRaw);
    #   OK/O.K. could either be "Oklahoma" or "Okay"
#         modRaw <- gsub("\\bACA OK\\b", "ACA OKay", modRaw); 
#         modRaw <- gsub("\\bNow O\\.K\\.\\b", "Now OKay", modRaw);        
    #   PR/P.R. could either be "PuertoRico" or "Public Relations"        
        # modRaw <- gsub("\\bP\\.R\\. Campaign", "PublicRelations Campaign", modRaw);        
    #   VA/V.A. could either be "Virginia" or "VeteransAdministration"        
        # modRaw <- gsub("\\bthe V\\.A\\.\\:", "the VeteranAffairs:", modRaw);
    #   
    # Custom mods

#         return(mod_raw) }

    # numeric
# Create feature based on record position/id in data   
glbFeatsDerive[[".pos"]] <- list(
    mapfn = function(.rnorm) { return(1:length(.rnorm)) }       
    , args = c(".rnorm"))    

# Add logs of numerics that are not distributed normally
#   Derive & keep multiple transformations of the same feature, if normality is hard to achieve with just one transformation
#   Right skew: logp1; sqrt; ^ 1/3; logp1(logp1); log10; exp(-<feat>/constant)
# glbFeatsDerive[["WordCount.log1p"]] <- list(
#     mapfn = function(WordCount) { return(log1p(WordCount)) } 
#   , args = c("WordCount"))
# glbFeatsDerive[["WordCount.root2"]] <- list(
#     mapfn = function(WordCount) { return(WordCount ^ (1/2)) } 
#   , args = c("WordCount"))
# glbFeatsDerive[["WordCount.nexp"]] <- list(
#     mapfn = function(WordCount) { return(exp(-WordCount)) } 
#   , args = c("WordCount"))
#print(summary(glbObsAll$WordCount))
#print(summary(mapfn(glbObsAll$WordCount)))
    
#     mapfn = function(HOSPI.COST) { return(cut(HOSPI.COST, 5, breaks = c(0, 100000, 200000, 300000, 900000), labels = NULL)) }     
#     mapfn = function(Rasmussen)  { return(ifelse(sign(Rasmussen) >= 0, 1, 0)) } 
#     mapfn = function(startprice) { return(startprice ^ (1/2)) }       
#     mapfn = function(startprice) { return(log(startprice)) }   
#     mapfn = function(startprice) { return(exp(-startprice / 20)) }
#     mapfn = function(startprice) { return(scale(log(startprice))) }     
#     mapfn = function(startprice) { return(sign(sprice.predict.diff) * (abs(sprice.predict.diff) ^ (1/10))) }        

    # factor      
glbFeatsDerive[["Pclass.fctr"]] <- list(
    mapfn = function(Pclass) { return(as.factor(Pclass)) } 
  , args = c("Pclass"))

#     mapfn = function(PropR) { return(as.factor(ifelse(PropR >= 0.5, "Y", "N"))) }
#     mapfn = function(productline, description) { as.factor(gsub(" ", "", productline)) }
#     mapfn = function(purpose) { return(relevel(as.factor(purpose), ref="all_other")) }
#     mapfn = function(raw) { tfr_raw <- as.character(cut(raw, 5)); 
#                             tfr_raw[is.na(tfr_raw)] <- "NA.my";
#                             return(as.factor(tfr_raw)) }
#     mapfn = function(startprice.log10) { return(cut(startprice.log10, 3)) }
#     mapfn = function(startprice.log10) { return(cut(sprice.predict.diff, c(-1000, -100, -10, -1, 0, 1, 10, 100, 1000))) }    

#     , args = c("<arg1>"))
    
    # multiple args
#     mapfn = function(id, date) { return(paste(as.character(id), as.character(date), sep = "#")) }        
#     mapfn = function(PTS, oppPTS) { return(PTS - oppPTS) }
#     mapfn = function(startprice.log10.predict, startprice) {
#                  return(spdiff <- (10 ^ startprice.log10.predict) - startprice) } 
#     mapfn = function(productline, description) { as.factor(
#         paste(gsub(" ", "", productline), as.numeric(nchar(description) > 0), sep = "*")) }
#     mapfn = function(.src, .pos) { 
#         return(paste(.src, sprintf("%04d", 
#                                    ifelse(.src == "Train", .pos, .pos - 7049)
#                                    ), sep = "#")) }       

# # If glbObsAll is not sorted in the desired manner
#     mapfn=function(Week) { return(coredata(lag(zoo(orderBy(~Week, glbObsAll)$ILI), -2, na.pad=TRUE))) }
#     mapfn=function(ILI) { return(coredata(lag(zoo(ILI), -2, na.pad=TRUE))) }
#     mapfn=function(ILI.2.lag) { return(log(ILI.2.lag)) }

# glbFeatsDerive[["<var1>"]] <- glbFeatsDerive[["<var2>"]]

glb_derive_vars <- names(glbFeatsDerive)

# tst <- "descr.my"; args_lst <- NULL; for (arg in glbFeatsDerive[[tst]]$args) args_lst[[arg]] <- glbObsAll[, arg]; print(head(args_lst[[arg]])); print(head(drv_vals <- do.call(glbFeatsDerive[[tst]]$mapfn, args_lst))); 
# print(which_ix <- which(args_lst[[arg]] == 0.75)); print(drv_vals[which_ix]); 

glbFeatsDateTime <- list()
# glbFeatsDateTime[["<DateTimeFeat>"]] <- 
#     c(format = "%Y-%m-%d %H:%M:%S", timezone = "America/New_York", impute.na = TRUE, 
#       last.ctg = TRUE, poly.ctg = TRUE)

glbFeatsPrice <- NULL # or c("<price_var>")

glbFeatsImage <- list() #list(<imageFeat> = list(patchSize = 10)) # if patchSize not specified, no patch computation

glbFeatsText <- list()
Sys.setlocale("LC_ALL", "C") # For english
## [1] "C/C/C/C/C/en_US.UTF-8"
#glbFeatsText[["<TextFeature>"]] <- list(NULL,
#   ,names = myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL, 
#       <comma-separated-screened-names>
#   ))))
#   ,rareWords = myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL, 
#       <comma-separated-nonSCOWL-words>
#   ))))
#)

# Text Processing Step: custom modifications not present in txt_munge -> use glbFeatsDerive
# Text Processing Step: universal modifications
glb_txt_munge_filenames_pfx <- "<projectId>_mytxt_"

# Text Processing Step: tolower
# Text Processing Step: myreplacePunctuation
# Text Processing Step: removeWords
glb_txt_stop_words <- list()
# Remember to use unstemmed words
if (length(glbFeatsText) > 0) {
    require(tm)
    require(stringr)

    glb_txt_stop_words[["<txt_var>"]] <- sort(myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
        # Remove any words from stopwords            
#         , setdiff(myreplacePunctuation(stopwords("english")), c("<keep_wrd1>", <keep_wrd2>"))
                                
        # Remove salutations
        ,"mr","mrs","dr","Rev"                                

        # Remove misc
        #,"th" # Happy [[:digit::]]+th birthday 

        # Remove terms present in Trn only or New only; search for "Partition post-stem"
        #   ,<comma-separated-terms>        

        # cor.y.train == NA
#         ,unlist(strsplit(paste(c(NULL
#           ,"<comma-separated-terms>"
#         ), collapse=",")

        # freq == 1; keep c("<comma-separated-terms-to-keep>")
            # ,<comma-separated-terms>

        # chisq.pval high (e.g. == 1); keep c("<comma-separated-terms-to-keep>")
            # ,<comma-separated-terms>

        # nzv.freqRatio high (e.g. >= glbFeatsNzvFreqMax); keep c("<comma-separated-terms-to-keep>")
            # ,<comma-separated-terms>        
                                            )))))
}
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^man", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
#glbObsAll[glb_post_stem_words_terms_mtrx_lst[[txtFeat]][, 4866] > 0, c(glb_rsp_var, txtFeat)]

# To identify terms with a specific freq
#paste0(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], freq == 1)$term), collapse = ",")
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], freq <= 2)$term), collapse = ",")
#subset(glb_post_stem_words_terms_df_lst[[txtFeat]], term %in% c("zinger"))

# To identify terms with a specific freq & 
#   are not stemmed together later OR is value of color.fctr (e.g. gold)
#paste0(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], (freq == 1) & !(term %in% c("blacked","blemish","blocked","blocks","buying","cables","careful","carefully","changed","changing","chargers","cleanly","cleared","connect","connects","connected","contains","cosmetics","default","defaulting","defective","definitely","describe","described","devices","displays","drop","drops","engravement","excellant","excellently","feels","fix","flawlessly","frame","framing","gentle","gold","guarantee","guarantees","handled","handling","having","install","iphone","iphones","keeped","keeps","known","lights","line","lining","liquid","liquidation","looking","lots","manuals","manufacture","minis","most","mostly","network","networks","noted","opening","operated","performance","performs","person","personalized","photograph","physically","placed","places","powering","pre","previously","products","protection","purchasing","returned","rotate","rotation","running","sales","second","seconds","shipped","shuts","sides","skin","skinned","sticker","storing","thats","theres","touching","unusable","update","updates","upgrade","weeks","wrapped","verified","verify") ))$term), collapse = ",")

#print(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (freq <= 2)))
#glbObsAll[which(terms_mtrx[, 229] > 0), glbFeatsText]

# To identify terms with cor.y == NA
#orderBy(~-freq+term, subset(glb_post_stop_words_terms_df_lst[[txtFeat]], is.na(cor.y)))
#paste(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], is.na(cor.y))[, "term"]), collapse=",")
#orderBy(~-freq+term, subset(glb_post_stem_words_terms_df_lst[[txtFeat]], is.na(cor.y)))

# To identify terms with low cor.y.abs
#head(orderBy(~cor.y.abs+freq+term, subset(glb_post_stem_words_terms_df_lst[[txtFeat]], !is.na(cor.y))), 5)

# To identify terms with high chisq.pval
#subset(glb_post_stem_words_terms_df_lst[[txtFeat]], chisq.pval > 0.99)
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (chisq.pval > 0.99) & (freq <= 10))$term), collapse=",")
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (chisq.pval > 0.9))$term), collapse=",")
#head(orderBy(~-chisq.pval+freq+term, glb_post_stem_words_terms_df_lst[[txtFeat]]), 5)
#glbObsAll[glb_post_stem_words_terms_mtrx_lst[[txtFeat]][, 68] > 0, glbFeatsText]
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^m", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])

# To identify terms with high nzv.freqRatio
#summary(glb_post_stem_words_terms_df_lst[[txtFeat]]$nzv.freqRatio)
#paste0(sort(setdiff(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (nzv.freqRatio >= glbFeatsNzvFreqMax) & (freq < 10) & (chisq.pval >= 0.05))$term, c( "128gb","3g","4g","gold","ipad1","ipad3","ipad4","ipadair2","ipadmini2","manufactur","spacegray","sprint","tmobil","verizon","wifion"))), collapse=",")

# To identify obs with a txt term
#tail(orderBy(~-freq+term, glb_post_stop_words_terms_df_lst[[txtFeat]]), 20)
#mydspObs(list(descr.my.contains="non"), cols=c("color", "carrier", "cellular", "storage"))
#grep("ever", dimnames(terms_stop_mtrx)$Terms)
#which(terms_stop_mtrx[, grep("ipad", dimnames(terms_stop_mtrx)$Terms)] > 0)
#glbObsAll[which(terms_stop_mtrx[, grep("16", dimnames(terms_stop_mtrx)$Terms)[1]] > 0), c(glbFeatsCategory, "storage", txtFeat)]

# Text Processing Step: screen for names # Move to glbFeatsText specs section in order of text processing steps
# glbFeatsText[["<txtFeat>"]]$names <- myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
#         # Person names for names screening
#         ,<comma-separated-list>
#         
#         # Company names
#         ,<comma-separated-list>
#                     
#         # Product names
#         ,<comma-separated-list>
#     ))))

# glbFeatsText[["<txtFeat>"]]$rareWords <- myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
#         # Words not in SCOWL db
#         ,<comma-separated-list>
#     ))))

# To identify char vectors post glbFeatsTextMap
#grep("six(.*)hour", glb_txt_chr_lst[[txtFeat]], ignore.case = TRUE, value = TRUE)
#grep("[S|s]ix(.*)[H|h]our", glb_txt_chr_lst[[txtFeat]], value = TRUE)

# To identify whether terms shd be synonyms
#orderBy(~term, glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^moder", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ])
# term_row_df <- glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^came$", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ]
# 
# cor(glb_post_stop_words_terms_mtrx_lst[[txtFeat]][glbObsAll$.lcn == "Fit", term_row_df$pos], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")

# To identify which stopped words are "close" to a txt term
#sort(cluster_vars)

# Text Processing Step: stemDocument
# To identify stemmed txt terms
#glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^la$", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ]
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^con", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
#glbObsAll[which(terms_stem_mtrx[, grep("use", dimnames(terms_stem_mtrx)$Terms)[[1]]] > 0), c(glbFeatsId, "productline", txtFeat)]
#glbObsAll[which(TfIdf_stem_mtrx[, 191] > 0), c(glbFeatsId, glbFeatsCategory, txtFeat)]
#glbObsAll[which(glb_post_stop_words_terms_mtrx_lst[[txtFeat]][, 6165] > 0), c(glbFeatsId, glbFeatsCategory, txtFeat)]
#which(glbObsAll$UniqueID %in% c(11915, 11926, 12198))

# Text Processing Step: mycombineSynonyms
#   To identify which terms are associated with not -> combine "could not" & "couldn't"
#findAssocs(glb_full_DTM_lst[[txtFeat]], "not", 0.05)
#   To identify which synonyms should be combined
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^c", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
chk_comb_cor <- function(syn_lst) {
#     cor(terms_stem_mtrx[glbObsAll$.src == "Train", grep("^(damag|dent|ding)$", dimnames(terms_stem_mtrx)[[2]])], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
    print(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], term %in% syn_lst$syns))
    print(subset(get_corpus_terms(tm_map(glbFeatsTextCorpus[[txtFeat]], mycombineSynonyms, list(syn_lst), lazy=FALSE)), term == syn_lst$word))
#     cor(terms_stop_mtrx[glbObsAll$.src == "Train", grep("^(damage|dent|ding)$", dimnames(terms_stop_mtrx)[[2]])], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
#     cor(rowSums(terms_stop_mtrx[glbObsAll$.src == "Train", grep("^(damage|dent|ding)$", dimnames(terms_stop_mtrx)[[2]])]), glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
}
#chk_comb_cor(syn_lst=list(word="cabl",  syns=c("cabl", "cord")))
#chk_comb_cor(syn_lst=list(word="damag",  syns=c("damag", "dent", "ding")))
#chk_comb_cor(syn_lst=list(word="dent",  syns=c("dent", "ding")))
#chk_comb_cor(syn_lst=list(word="use",  syns=c("use", "usag")))

glbFeatsTextSynonyms <- list()
# list parsed to collect glbFeatsText[[<txtFeat>]]$vldTerms
# glbFeatsTextSynonyms[["Hdln.my"]] <- list(NULL
#     # people in places
#     , list(word = "australia", syns = c("australia", "australian"))
#     , list(word = "italy", syns = c("italy", "Italian"))
#     , list(word = "newyork", syns = c("newyork", "newyorker"))    
#     , list(word = "Pakistan", syns = c("Pakistan", "Pakistani"))    
#     , list(word = "peru", syns = c("peru", "peruvian"))
#     , list(word = "qatar", syns = c("qatar", "qatari"))
#     , list(word = "scotland", syns = c("scotland", "scotish"))
#     , list(word = "Shanghai", syns = c("Shanghai", "Shanzhai"))    
#     , list(word = "venezuela", syns = c("venezuela", "venezuelan"))    
# 
#     # companies - needs to be data dependent 
#     #   - e.g. ensure BNP in this experiment/feat always refers to BNPParibas
#         
#     # general synonyms
#     , list(word = "Create", syns = c("Create","Creator")) 
#     , list(word = "cute", syns = c("cute","cutest"))     
#     , list(word = "Disappear", syns = c("Disappear","Fadeout"))     
#     , list(word = "teach", syns = c("teach", "taught"))     
#     , list(word = "theater",  syns = c("theater", "theatre", "theatres")) 
#     , list(word = "understand",  syns = c("understand", "understood"))    
#     , list(word = "weak",  syns = c("weak", "weaken", "weaker", "weakest"))
#     , list(word = "wealth",  syns = c("wealth", "wealthi"))    
#     
#     # custom synonyms (phrases)
#     
#     # custom synonyms (names)
#                                       )
#glbFeatsTextSynonyms[["<txtFeat>"]] <- list(NULL
#     , list(word="<stem1>",  syns=c("<stem1>", "<stem1_2>"))
#                                       )

for (txtFeat in names(glbFeatsTextSynonyms))
    for (entryIx in 1:length(glbFeatsTextSynonyms[[txtFeat]])) {
        glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$word <-
            str_to_lower(glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$word)
        glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$syns <-
            str_to_lower(glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$syns)        
    }        

glbFeatsTextSeed <- 181
# tm options include: check tm::weightSMART 
glb_txt_terms_control <- list( # Gather model performance & run-time stats
                    # weighting = function(x) weightSMART(x, spec = "nnn")
                    # weighting = function(x) weightSMART(x, spec = "lnn")
                    # weighting = function(x) weightSMART(x, spec = "ann")
                    # weighting = function(x) weightSMART(x, spec = "bnn")
                    # weighting = function(x) weightSMART(x, spec = "Lnn")
                    # 
                    weighting = function(x) weightSMART(x, spec = "ltn") # default
                    # weighting = function(x) weightSMART(x, spec = "lpn")                    
                    # 
                    # weighting = function(x) weightSMART(x, spec = "ltc")                    
                    # 
                    # weighting = weightBin 
                    # weighting = weightTf 
                    # weighting = weightTfIdf # : default
                # termFreq selection criteria across obs: tm default: list(global=c(1, Inf))
                    , bounds = list(global = c(1, Inf)) 
                # wordLengths selection criteria: tm default: c(3, Inf)
                    , wordLengths = c(1, Inf) 
                              ) 

glb_txt_cor_var <- glb_rsp_var # : default # or c(<feat>)

# select one from c("union.top.val.cor", "top.cor", "top.val", default: "top.chisq", "sparse")
glbFeatsTextFilter <- "top.chisq" 
glbFeatsTextTermsMax <- rep(10, length(glbFeatsText)) # :default
names(glbFeatsTextTermsMax) <- names(glbFeatsText)

# Text Processing Step: extractAssoc
glbFeatsTextAssocCor <- rep(1, length(glbFeatsText)) # :default 
names(glbFeatsTextAssocCor) <- names(glbFeatsText)

# Remember to use stemmed terms
glb_important_terms <- list()

# Text Processing Step: extractPatterns (ngrams)
glbFeatsTextPatterns <- list()
#glbFeatsTextPatterns[[<txtFeat>>]] <- list()
#glbFeatsTextPatterns[[<txtFeat>>]] <- c(metropolitan.diary.colon = "Metropolitan Diary:")

# Have to set it even if it is not used
# Properties:
#   numrows(glb_feats_df) << numrows(glbObsFit
#   Select terms that appear in at least 0.2 * O(FP/FN(glbObsOOB)) ???
#       numrows(glbObsOOB) = 1.1 * numrows(glbObsNew) ???
glb_sprs_thresholds <- NULL # or c(<txtFeat1> = 0.988, <txtFeat2> = 0.970, <txtFeat3> = 0.970)

glbFctrMaxUniqVals <- 20 # default: 20
glb_impute_na_data <- FALSE # or TRUE
glb_mice_complete.seed <- 144 # or any integer

glb_cluster <- FALSE # : default or TRUE
glb_cluster.seed <- 189 # or any integer
glb_cluster_entropy_var <- NULL # c(glb_rsp_var, as.factor(cut(glb_rsp_var, 3)), default: NULL)
glbFeatsTextClusterVarsExclude <- FALSE # default FALSE

glb_interaction_only_feats <- NULL # : default or c(<parent_feat> = "<child_feat>")

glbFeatsNzvFreqMax <- 19 # 19 : caret default
glbFeatsNzvUniqMin <- 10 # 10 : caret default

glbRFESizes <- list()
#glbRFESizes[["mdlFamily"]] <- c(4, 8, 16, 32, 64, 67, 68, 69) # Accuracy@69/70 = 0.8258

glbObsFitOutliers <- list()
# If outliers.n >= 10; consider concatenation of interaction vars
# glbObsFitOutliers[["<mdlFamily>"]] <- c(NULL
#     is.na(.rstudent)
#     max(.rstudent)
#     is.na(.dffits)
#     .hatvalues >= 0.99        
#     -38,167,642 < minmax(.rstudent) < 49,649,823    
#     , <comma-separated-<glbFeatsId>>
#                                     )
glbObsTrnOutliers <- list()
glbObsTrnOutliers[["Final"]] <- union(glbObsFitOutliers[["All.X"]],
                                c(NULL
                                ))

# influence.measures: car::outlier; rstudent; dffits; hatvalues; dfbeta; dfbetas
#mdlId <- "All.X##rcv#glm"; obs_df <- fitobs_df
#mdlId <- "RFE.X.glm"; obs_df <- fitobs_df
#mdlId <- "Final.glm"; obs_df <- trnobs_df
#mdlId <- "CSM2.X.glm"; obs_df <- fitobs_df
#print(outliers <- car::outlierTest(glb_models_lst[[mdlId]]$finalModel))
#mdlIdFamily <- paste0(head(unlist(str_split(mdlId, "\\.")), -1), collapse="."); obs_df <- dplyr::filter_(obs_df, interp(~(!(var %in% glbObsFitOutliers[[mdlIdFamily]])), var = as.name(glbFeatsId))); model_diags_df <- cbind(obs_df, data.frame(.rstudent=stats::rstudent(glb_models_lst[[mdlId]]$finalModel)), data.frame(.dffits=stats::dffits(glb_models_lst[[mdlId]]$finalModel)), data.frame(.hatvalues=stats::hatvalues(glb_models_lst[[mdlId]]$finalModel)));print(summary(model_diags_df[, c(".rstudent",".dffits",".hatvalues")])); table(cut(model_diags_df$.hatvalues, breaks=c(0.00, 0.98, 0.99, 1.00)))

#print(subset(model_diags_df, is.na(.rstudent))[, glbFeatsId])
#print(model_diags_df[which.max(model_diags_df$.rstudent), ])
#print(subset(model_diags_df, is.na(.dffits))[, glbFeatsId])
#print(model_diags_df[which.min(model_diags_df$.dffits), ])
#print(subset(model_diags_df, .hatvalues > 0.99)[, glbFeatsId])
#dffits_df <- merge(dffits_df, outliers_df, by="row.names", all.x=TRUE); row.names(dffits_df) <- dffits_df$Row.names; dffits_df <- subset(dffits_df, select=-Row.names)
#dffits_df <- merge(dffits_df, glbObsFit, by="row.names", all.x=TRUE); row.names(dffits_df) <- dffits_df$Row.names; dffits_df <- subset(dffits_df, select=-Row.names)
#subset(dffits_df, !is.na(.Bonf.p))

#mdlId <- "CSM.X.glm"; vars <- myextract_actual_feats(row.names(orderBy(reformulate(c("-", paste0(mdlId, ".imp"))), myget_feats_imp(glb_models_lst[[mdlId]])))); 
#model_diags_df <- glb_get_predictions(model_diags_df, mdlId, glb_rsp_var)
#obs_ix <- row.names(model_diags_df) %in% names(outliers$rstudent)[1]
#obs_ix <- which(is.na(model_diags_df$.rstudent))
#obs_ix <- which(is.na(model_diags_df$.dffits))
#myplot_parcoord(obs_df=model_diags_df[, c(glbFeatsId, glbFeatsCategory, ".rstudent", ".dffits", ".hatvalues", glb_rsp_var, paste0(glb_rsp_var, mdlId), vars[1:min(20, length(vars))])], obs_ix=obs_ix, id_var=glbFeatsId, category_var=glbFeatsCategory)

#model_diags_df[row.names(model_diags_df) %in% names(outliers$rstudent)[c(1:2)], ]
#ctgry_diags_df <- model_diags_df[model_diags_df[, glbFeatsCategory] %in% c("Unknown#0"), ]
#myplot_parcoord(obs_df=ctgry_diags_df[, c(glbFeatsId, glbFeatsCategory, ".rstudent", ".dffits", ".hatvalues", glb_rsp_var, "startprice.log10.predict.RFE.X.glmnet", indep_vars[1:20])], obs_ix=row.names(ctgry_diags_df) %in% names(outliers$rstudent)[1], id_var=glbFeatsId, category_var=glbFeatsCategory)
#table(glbObsFit[model_diags_df[, glbFeatsCategory] %in% c("iPad1#1"), "startprice.log10.cut.fctr"])
#glbObsFit[model_diags_df[, glbFeatsCategory] %in% c("iPad1#1"), c(glbFeatsId, "startprice")]

# No outliers & .dffits == NaN
#myplot_parcoord(obs_df=model_diags_df[, c(glbFeatsId, glbFeatsCategory, glb_rsp_var, "startprice.log10.predict.RFE.X.glmnet", indep_vars[1:10])], obs_ix=seq(1:nrow(model_diags_df))[is.na(model_diags_df$.dffits)], id_var=glbFeatsId, category_var=glbFeatsCategory)

# Modify mdlId to (build & extract) "<FamilyId>#<Fit|Trn>#<caretMethod>#<preProc1.preProc2>#<samplingMethod>"
glb_models_lst <- list(); glb_models_df <- data.frame()
# Regression
if (glb_is_regression) {
    glbMdlMethods <- c(NULL
        # deterministic
            #, "lm", # same as glm
            , "glm", "bayesglm", "glmnet"
            , "rpart"
        # non-deterministic
            , "gbm", "rf" 
        # Unknown
            , "nnet" , "avNNet" # runs 25 models per cv sample for tunelength=5
            , "svmLinear", "svmLinear2"
            , "svmPoly" # runs 75 models per cv sample for tunelength=5
            , "svmRadial" 
            , "earth"
            , "bagEarth" # Takes a long time
        )
} else
# Classification - Add ada (auto feature selection)
    if (glb_is_binomial)
        glbMdlMethods <- c(NULL
        # deterministic                     
            , "bagEarth" # Takes a long time        
            , "glm", "bayesglm", "glmnet"
            , "nnet"
            , "rpart"
        # non-deterministic        
            , "gbm"
            , "avNNet" # runs 25 models per cv sample for tunelength=5      
            , "rf"
        # Unknown
            , "lda", "lda2"
                # svm models crash when predict is called -> internal to kernlab it should call predict without .outcome
            , "svmLinear", "svmLinear2"
            , "svmPoly" # runs 75 models per cv sample for tunelength=5
            , "svmRadial" 
            , "earth"
        ) else
        glbMdlMethods <- c(NULL
        # deterministic
            ,"glmnet"
        # non-deterministic 
            ,"rf"       
        # Unknown
            ,"gbm","rpart"
        )

glbMdlFamilies <- list(); glb_mdl_feats_lst <- list()
# family: Choose from c("RFE.X", "CSM.X", "All.X", "Best.Interact")
#   methods: Choose from c(NULL, <method>, glbMdlMethods) 
#glbMdlFamilies[["RFE.X"]] <- c("glmnet", "glm") # non-NULL vector is mandatory
glbMdlFamilies[["All.X"]] <- c("glmnet", "glm")  # non-NULL vector is mandatory
#glbMdlFamilies[["Best.Interact"]] <- "glmnet" # non-NULL vector is mandatory

# Check if interaction features make RFE better
# glbMdlFamilies[["CSM.X"]] <- setdiff(glbMdlMethods, c("lda", "lda2")) # crashing due to category:.clusterid ??? #c("glmnet", "glm") # non-NULL list is mandatory
# glb_mdl_feats_lst[["CSM.X"]] <- c(NULL
#     , <comma-separated-features-vector>
#                                   )
# dAFeats.CSM.X %<d-% c(NULL
#     # Interaction feats up to varImp(RFE.X.glmnet) >= 50
#     , <comma-separated-features-vector>
#     , setdiff(myextract_actual_feats(predictors(rfe_fit_results)), c(NULL
#                , <comma-separated-features-vector>
#                                                                       ))    
#                                   )
# glb_mdl_feats_lst[["CSM.X"]] <- "%<d-% dAFeats.CSM.X"

glbMdlFamilies[["Final"]] <- c(NULL) # NULL vector acceptable # c("glmnet", "glm")

glbMdlAllowParallel <- list()
#glbMdlAllowParallel[["<mdlId>"]] <- FALSE

# Check if tuning parameters make fit better; make it mdlFamily customizable ?
glbMdlTuneParams <- data.frame()
# When glmnet crashes at model$grid with error: ???
glmnetTuneParams <- rbind(data.frame()
                        ,data.frame(parameter = "alpha",  vals = "0.100 0.325 0.550 0.775 1.000")
                        ,data.frame(parameter = "lambda", vals = "9.342e-02")    
                        )
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams,
#                                cbind(data.frame(mdlId = "<mdlId>"),
#                                      glmnetTuneParams))

    #avNNet    
    #   size=[1] 3 5 7 9; decay=[0] 1e-04 0.001  0.01   0.1; bag=[FALSE]; RMSE=1.3300906 

    #bagEarth
    #   degree=1 [2] 3; nprune=64 128 256 512 [1024]; RMSE=0.6486663 (up)
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "bagEarth", parameter = "nprune", vals = "256")
#     ,data.frame(method = "bagEarth", parameter = "degree", vals = "2")    
# ))

    #earth 
    #   degree=[1]; nprune=2  [9] 17 25 33; RMSE=0.1334478
    
    #gbm 
    #   shrinkage=0.05 [0.10] 0.15 0.20 0.25; n.trees=100 150 200 [250] 300; interaction.depth=[1] 2 3 4 5; n.minobsinnode=[10]; RMSE=0.2008313     
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "gbm", parameter = "shrinkage", min = 0.05, max = 0.25, by = 0.05)
#     ,data.frame(method = "gbm", parameter = "n.trees", min = 100, max = 300, by = 50)
#     ,data.frame(method = "gbm", parameter = "interaction.depth", min = 1, max = 5, by = 1)
#     ,data.frame(method = "gbm", parameter = "n.minobsinnode", min = 10, max = 10, by = 10)
#     #seq(from=0.05,  to=0.25, by=0.05)
# ))

    #glmnet
    #   alpha=0.100 [0.325] 0.550 0.775 1.000; lambda=0.0005232693 0.0024288010 0.0112734954 [0.0523269304] 0.2428800957; RMSE=0.6164891
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "glmnet", parameter = "alpha", vals = "0.550 0.775 0.8875 0.94375 1.000")
#     ,data.frame(method = "glmnet", parameter = "lambda", vals = "9.858855e-05 0.0001971771 0.0009152152 0.0042480525 0.0197177130")    
# ))

    #nnet    
    #   size=3 5 [7] 9 11; decay=0.0001 0.001 0.01 [0.1] 0.2; RMSE=0.9287422
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "nnet", parameter = "size", vals = "3 5 7 9 11")
#     ,data.frame(method = "nnet", parameter = "decay", vals = "0.0001 0.0010 0.0100 0.1000 0.2000")    
# ))

    #rf # Don't bother; results are not deterministic
    #       mtry=2  35  68 [101] 134; RMSE=0.1339974
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "rf", parameter = "mtry", vals = "2 5 9 13 17")
# ))

    #rpart 
    #   cp=0.020 [0.025] 0.030 0.035 0.040; RMSE=0.1770237
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()    
#     ,data.frame(method = "rpart", parameter = "cp", vals = "0.004347826 0.008695652 0.017391304 0.021739130 0.034782609")
# ))
    
    #svmLinear
    #   C=0.01 0.05 [0.10] 0.50 1.00 2.00 3.00 4.00; RMSE=0.1271318; 0.1296718
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "svmLinear", parameter = "C", vals = "0.01 0.05 0.1 0.5 1")
# ))

    #svmLinear2    
    #   cost=0.0625 0.1250 [0.25] 0.50 1.00; RMSE=0.1276354 
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "svmLinear2", parameter = "cost", vals = "0.0625 0.125 0.25 0.5 1")
# ))

    #svmPoly    
    #   degree=[1] 2 3 4 5; scale=0.01 0.05 [0.1] 0.5 1; C=0.50 1.00 [2.00] 3.00 4.00; RMSE=0.1276130
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method="svmPoly", parameter="degree", min=1, max=5, by=1) #seq(1, 5, 1)
#     ,data.frame(method="svmPoly", parameter="scale", vals="0.01, 0.05, 0.1, 0.5, 1")
#     ,data.frame(method="svmPoly", parameter="C", vals="0.50, 1.00, 2.00, 3.00, 4.00")    
# ))

    #svmRadial
    #   sigma=[0.08674323]; C=0.25 0.50 1.00 [2.00] 4.00; RMSE=0.1614957
    
#glb2Sav(); all.equal(sav_models_df, glb_models_df)
    
glb_preproc_methods <- NULL
#     c("YeoJohnson", "center.scale", "range", "pca", "ica", "spatialSign")

# Baseline prediction model feature(s)
glb_Baseline_mdl_var <- NULL # or c("<feat>")

glbMdlMetric_terms <- NULL # or matrix(c(
#                               0,1,2,3,4,
#                               2,0,1,2,3,
#                               4,2,0,1,2,
#                               6,4,2,0,1,
#                               8,6,4,2,0
#                           ), byrow=TRUE, nrow=5)
glbMdlMetricSummary <- NULL # or "<metric_name>"
glbMdlMetricMaximize <- NULL # or FALSE (TRUE is not the default for both classification & regression) 
glbMdlMetricSummaryFn <- NULL # or function(data, lev=NULL, model=NULL) {
#     confusion_mtrx <- t(as.matrix(confusionMatrix(data$pred, data$obs)))
#     #print(confusion_mtrx)
#     #print(confusion_mtrx * glbMdlMetric_terms)
#     metric <- sum(confusion_mtrx * glbMdlMetric_terms) / nrow(data)
#     names(metric) <- glbMdlMetricSummary
#     return(metric)
# }

glbMdlCheckRcv <- FALSE # Turn it on when needed; otherwise takes long time
glb_rcv_n_folds <- 3 # or NULL
glb_rcv_n_repeats <- 3 # or NULL

glb_clf_proba_threshold <- NULL # 0.5

# Model selection criteria
if (glb_is_regression)
    glbMdlMetricsEval <- c("min.RMSE.OOB", "max.R.sq.OOB", "max.Adj.R.sq.fit", "min.RMSE.fit")
    #glbMdlMetricsEval <- c("min.RMSE.fit", "max.R.sq.fit", "max.Adj.R.sq.fit")    
if (glb_is_classification) {
    if (glb_is_binomial)
        glbMdlMetricsEval <- 
            c("max.Accuracy.OOB", "max.AUCROCR.OOB", "max.AUCpROC.OOB", "min.aic.fit", "max.Accuracy.fit") else        
        glbMdlMetricsEval <- c("max.Accuracy.OOB", "max.Kappa.OOB")
}

# select from NULL [no ensemble models], "auto" [all models better than MFO or Baseline], c(mdl_ids in glb_models_lst) [Typically top-rated models in auto]
glb_mdl_ensemble <- NULL
#     "%<d-% setdiff(mygetEnsembleAutoMdlIds(), 'CSM.X.rf')" 
#     c(<comma-separated-mdlIds>
#      )

# Only for classifications; for regressions remove "(.*)\\.prob" form the regex
# tmp_fitobs_df <- glbObsFit[, grep(paste0("^", gsub(".", "\\.", mygetPredictIds$value, fixed = TRUE), "CSM\\.X\\.(.*)\\.prob"), names(glbObsFit), value = TRUE)]; cor_mtrx <- cor(tmp_fitobs_df); cor_vctr <- sort(cor_mtrx[row.names(orderBy(~-Overall, varImp(glb_models_lst[["Ensemble.repeatedcv.glmnet"]])$imp))[1], ]); summary(cor_vctr); cor_vctr
#ntv.glm <- glm(reformulate(indep_vars, glb_rsp_var), family = "binomial", data = glbObsFit)
#step.glm <- step(ntv.glm)

glb_sel_mdl_id <- "All.X##rcv#glmnet" #select from c(NULL, "All.X##rcv#glmnet", "RFE.X##rcv#glmnet", <mdlId>)
glb_fin_mdl_id <- NULL #select from c(NULL, glb_sel_mdl_id)

glb_dsp_cols <- c(".pos", glbFeatsId, glbFeatsCategory, glb_rsp_var
#               List critical cols excl. above
                  )

# Output specs
# lclgetfltout_df <- function(obsout_df) {
#     require(tidyr)
#     obsout_df <- obsout_df %>%
#         tidyr::separate("ImageId.x.y", c(".src", ".pos", "x", "y"), 
#                         sep = "#", remove = TRUE, extra = "merge")
#     # mnm prefix stands for max_n_mean
#     mnmout_df <- obsout_df %>%
#         dplyr::group_by(.pos) %>%
#         #dplyr::top_n(1, Probability1) %>% # Score = 3.9426         
#         #dplyr::top_n(2, Probability1) %>% # Score = ???; weighted = 3.94254;         
#         #dplyr::top_n(3, Probability1) %>% # Score = 3.9418; weighted = 3.94169; 
#         dplyr::top_n(4, Probability1) %>% # Score = ???; weighted = 3.94149;        
#         #dplyr::top_n(5, Probability1) %>% # Score = 3.9421; weighted = 3.94178
#     
#         # dplyr::summarize(xMeanN = mean(as.numeric(x)), yMeanN = mean(as.numeric(y)))
#         # dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), Probability1), yMeanN = mean(as.numeric(y)))
#         # dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), c(Probability1, 0.2357323, 0.2336925)), yMeanN = mean(as.numeric(y)))    
#         # dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), c(Probability1)), yMeanN = mean(as.numeric(y)))
#         dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), c(Probability1)), 
#                          yMeanN = weighted.mean(as.numeric(y), c(Probability1)))  
#     
#     maxout_df <- obsout_df %>%
#         dplyr::group_by(.pos) %>%
#         dplyr::summarize(maxProb1 = max(Probability1))
#     fltout_df <- merge(maxout_df, obsout_df, 
#                        by.x = c(".pos", "maxProb1"), by.y = c(".pos", "Probability1"),
#                        all.x = TRUE)
#     fmnout_df <- merge(fltout_df, mnmout_df, 
#                        by.x = c(".pos"), by.y = c(".pos"),
#                        all.x = TRUE)
#     return(fmnout_df)
# }
glbObsOut <- list(NULL
        # glbFeatsId will be the first output column, by default
        ,vars = list()
#         ,mapFn = function(obsout_df) {
#                     require(tidyr)
#                     smpout_df <- read.csv('data/IdLookupTable.csv')
#                     tmpout_df <- obsout_df %>% 
#                                     tidyr::gather(key = FeatureName, value = Location, -ImageId) %>%
#                                     merge(smpout_df[, -4], all.y = TRUE, sort = FALSE) %>%
#                                     select(matches("(RowId|Location)"))
#                     return(tmpout_df <- orderBy(~RowId, tmpout_df[, c("RowId", "Location")]))
#                   }
#         ,mapFn = function(obsout_df) {
#                     #sav_obsout_df <- obsout_df; all.equal(sav_obsout_df, obsout_df)
#                     fltout_df <- lclgetfltout_df(obsout_df) %>%
#                         dplyr::mutate(ImageId = as.integer(.pos)) %>%
#                         dplyr::select(ImageId, left_eye_center_x = x, left_eye_center_y = y) 
#                     smpout_df <- read.csv('data/IdLookupTable.csv')
#                     curout_df <- fltout_df %>% 
#                                     tidyr::gather(key = FeatureName, value = Location, -ImageId) %>%
#                                     merge(smpout_df[, -4], all.y = TRUE, sort = FALSE) %>%
#                                     dplyr::select(matches("(RowId|Location)")) %>%
#                                     dplyr::filter(!is.na(Location))
#                     prvout_df <- read.csv('Faces_patch_out.csv')
#                     thsout_df <- rbind(curout_df, subset(prvout_df, !(RowId %in% curout_df$RowId)))
#                     return(thsout_df <- orderBy(~RowId, thsout_df[, c("RowId", "Location")]))
#                  }
                  )
#obsout_df <- savobsout_df
# glbObsOut$mapFn <- function(obsout_df) {
#     txfout_df <- dplyr::select(obsout_df, -.pos.y) %>%
#         dplyr::mutate(
#             lunch     = levels(glbObsTrn[, "lunch"    ])[
#                        round(mean(as.numeric(glbObsTrn[, "lunch"    ])), 0)],
#             dinner    = levels(glbObsTrn[, "dinner"   ])[
#                        round(mean(as.numeric(glbObsTrn[, "dinner"   ])), 0)],
#             reserve   = levels(glbObsTrn[, "reserve"  ])[
#                        round(mean(as.numeric(glbObsTrn[, "reserve"  ])), 0)],
#             outdoor   = levels(glbObsTrn[, "outdoor"  ])[
#                        round(mean(as.numeric(glbObsTrn[, "outdoor"  ])), 0)],
#             expensive = levels(glbObsTrn[, "expensive"])[
#                        round(mean(as.numeric(glbObsTrn[, "expensive"])), 0)],
#             liquor    = levels(glbObsTrn[, "liquor"   ])[
#                        round(mean(as.numeric(glbObsTrn[, "liquor"   ])), 0)],
#             table     = levels(glbObsTrn[, "table"    ])[
#                        round(mean(as.numeric(glbObsTrn[, "table"    ])), 0)],
#             classy    = levels(glbObsTrn[, "classy"   ])[
#                        round(mean(as.numeric(glbObsTrn[, "classy"   ])), 0)],
#             kids      = levels(glbObsTrn[, "kids"     ])[
#                        round(mean(as.numeric(glbObsTrn[, "kids"     ])), 0)]
#                       )
#     
#     print("ObsNew output class tables:")
#     print(sapply(c("lunch","dinner","reserve","outdoor",
#                    "expensive","liquor","table",
#                    "classy","kids"), 
#                  function(feat) table(txfout_df[, feat], useNA = "ifany")))
#     
#     txfout_df <- txfout_df %>%
#         dplyr::mutate(labels = "") %>%
#         dplyr::mutate(labels = 
#     ifelse(lunch     != "-1", paste(labels, lunch    ), labels)) %>%
#         dplyr::mutate(labels = 
#     ifelse(dinner    != "-1", paste(labels, dinner   ), labels)) %>%
#         dplyr::mutate(labels = 
#     ifelse(reserve   != "-1", paste(labels, reserve  ), labels)) %>%
#         dplyr::mutate(labels = 
#     ifelse(outdoor   != "-1", paste(labels, outdoor  ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(expensive != "-1", paste(labels, expensive), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(liquor    != "-1", paste(labels, liquor   ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(table     != "-1", paste(labels, table    ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(classy    != "-1", paste(labels, classy   ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(kids      != "-1", paste(labels, kids     ), labels)) %>%
#         dplyr::select(business_id, labels)
#     return(txfout_df)
# }
#if (!is.null(glbObsOut$mapFn)) obsout_df <- glbObsOut$mapFn(obsout_df); print(head(obsout_df))

glb_out_obs <- NULL # select from c(NULL : default to "new", "all", "new", "trn")

if (glb_is_classification && glb_is_binomial) {
#     glbObsOut$vars[["Probability1"]] <- 
#         "%<d-% glbObsNew[, mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$prob]" 
    glbObsOut$vars[[glb_rsp_var_raw]] <- 
        "%<d-% glb_map_rsp_var_to_raw(glbObsNew[, 
                                            mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$value])" 
} else {
#     glbObsOut$vars[[glbFeatsId]] <- 
#         "%<d-% as.integer(gsub('Test#', '', glbObsNew[, glbFeatsId]))"
    glbObsOut$vars[[glb_rsp_var]] <- 
        "%<d-% glbObsNew[, mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$value]"
#     for (outVar in setdiff(glbFeatsExcludeLcl, glb_rsp_var_raw))
#         glbObsOut$vars[[outVar]] <- 
#             paste0("%<d-% mean(glbObsAll[, \"", outVar, "\"], na.rm = TRUE)")
}    
# glbObsOut$vars[[glb_rsp_var_raw]] <- glb_rsp_var_raw
# glbObsOut$vars[[paste0(head(unlist(strsplit(mygetPredictIds$value, "")), -1), collapse = "")]] <-

glbOutStackFnames <- NULL #: default
    # c("ebayipads_txt_assoc1_out_bid1_stack.csv") # manual stack
    # c("ebayipads_finmdl_bid1_out_nnet_1.csv") # universal stack

glbOut <- list(pfx = "Titanic_Pclass_")
# lclImageSampleSeed <- 129
glbOutDataVizFname <- NULL # choose from c(NULL, "<projectId>_obsall.csv")


glbChunks <- list(labels = c("set_global_options_wd","set_global_options"
    ,"import.data","inspect.data","scrub.data","transform.data"
    ,"extract.features"
        ,"extract.features.datetime","extract.features.image","extract.features.price"
        ,"extract.features.text","extract.features.string"  
        ,"extract.features.end"
    ,"manage.missing.data","cluster.data","partition.data.training","select.features"
    ,"fit.models_0","fit.models_1","fit.models_2","fit.models_3"
    ,"fit.data.training_0","fit.data.training_1"
    ,"predict.data.new"         
    ,"display.session.info"))
# To ensure that all chunks in this script are in glbChunks
if (!is.null(chkChunksLabels <- knitr::all_labels()) && # knitr::all_labels() doesn't work in console runs
    !identical(chkChunksLabels, glbChunks$labels)) {
    print(sprintf("setdiff(chkChunksLabels, glbChunks$labels): %s", 
                  setdiff(chkChunksLabels, glbChunks$labels)))    
    print(sprintf("setdiff(glbChunks$labels, chkChunksLabels): %s", 
                  setdiff(glbChunks$labels, chkChunksLabels)))    
}

glbChunks[["first"]] <- NULL #default: script will load envir from previous chunk
glbChunks[["last"]] <- NULL #"extract.features.end" #NULL #default: script will save envir at end of this chunk 
#mysavChunk(glbOut$pfx, glbChunks[["last"]])

# Inspect max OOB FP
#chkObsOOB <- subset(glbObsOOB, !label.fctr.All.X..rcv.glmnet.is.acc)
#chkObsOOBFP <- subset(chkObsOOB, label.fctr.All.X..rcv.glmnet == "left_eye_center") %>% dplyr::mutate(Probability1 = label.fctr.All.X..rcv.glmnet.prob) %>% select(-.src, -.pos, -x, -y) %>% lclgetfltout_df() %>% mutate(obj.distance = (((as.numeric(x) - left_eye_center_x.int) ^ 2) + ((as.numeric(y) - left_eye_center_y.int) ^ 2)) ^ 0.5) %>% dplyr::top_n(5, obj.distance) %>% dplyr::top_n(5, -patch.cor)
#
#newImgObs <- glbObsNew[(glbObsNew$ImageId == "Test#0001"), ]; print(newImgObs[which.max(newImgObs$label.fctr.Final..rcv.glmnet.prob), ])
#OOBImgObs <- glbObsOOB[(glbObsOOB$ImageId == "Train#0003"), ]; print(OOBImgObs[which.max(OOBImgObs$label.fctr.All.X..rcv.glmnet.prob), ])

#load("Titanic_tmplt_extract.features.end.RData", verbose = TRUE)
#mygetImage(which(glbObsAll[, glbFeatsId] == "Train#0003"), names(glbFeatsImage)[1], plot = TRUE, featHighlight = c("left_eye_center_x", "left_eye_center_y"), ovrlHighlight = c(66, 35))

# Depict process
glb_analytics_pn <- petrinet(name = "glb_analytics_pn",
                        trans_df = data.frame(id = 1:6,
    name = c("data.training.all","data.new",
           "model.selected","model.final",
           "data.training.all.prediction","data.new.prediction"),
    x=c(   -5,-5,-15,-25,-25,-35),
    y=c(   -5, 5,  0,  0, -5,  5)
                        ),
                        places_df=data.frame(id=1:4,
    name=c("bgn","fit.data.training.all","predict.data.new","end"),
    x=c(   -0,   -20,                    -30,               -40),
    y=c(    0,     0,                      0,                 0),
    M0=c(   3,     0,                      0,                 0)
                        ),
                        arcs_df = data.frame(
    begin = c("bgn","bgn","bgn",        
            "data.training.all","model.selected","fit.data.training.all",
            "fit.data.training.all","model.final",    
            "data.new","predict.data.new",
            "data.training.all.prediction","data.new.prediction"),
    end   = c("data.training.all","data.new","model.selected",
            "fit.data.training.all","fit.data.training.all","model.final",
            "data.training.all.prediction","predict.data.new",
            "predict.data.new","data.new.prediction",
            "end","end")
                        ))
#print(ggplot.petrinet(glb_analytics_pn))
print(ggplot.petrinet(glb_analytics_pn) + coord_flip())
## Loading required package: grid

glb_analytics_avl_objs <- NULL

glb_chunks_df <- myadd_chunk(NULL, "import.data")
##         label step_major step_minor label_minor   bgn end elapsed
## 1 import.data          1          0           0 9.263  NA      NA

Step 1.0: import data

chunk option: eval=

## [1] "Reading file ./data/train.csv..."
## [1] "dimensions of data in ./data/train.csv: 891 rows x 12 cols"
##   PassengerId Survived Pclass
## 1           1        0      3
## 2           2        1      1
## 3           3        1      3
## 4           4        1      1
## 5           5        0      3
## 6           6        0      3
##                                                  Name    Sex Age SibSp
## 1                             Braund, Mr. Owen Harris   male  22     1
## 2 Cumings, Mrs. John Bradley (Florence Briggs Thayer) female  38     1
## 3                              Heikkinen, Miss. Laina female  26     0
## 4        Futrelle, Mrs. Jacques Heath (Lily May Peel) female  35     1
## 5                            Allen, Mr. William Henry   male  35     0
## 6                                    Moran, Mr. James   male  NA     0
##   Parch           Ticket    Fare Cabin Embarked
## 1     0        A/5 21171  7.2500              S
## 2     0         PC 17599 71.2833   C85        C
## 3     0 STON/O2. 3101282  7.9250              S
## 4     0           113803 53.1000  C123        S
## 5     0           373450  8.0500              S
## 6     0           330877  8.4583              Q
##     PassengerId Survived Pclass
## 31           31        0      1
## 136         136        0      2
## 454         454        1      1
## 648         648        1      1
## 652         652        1      2
## 880         880        1      1
##                                              Name    Sex Age SibSp Parch
## 31                       Uruchurtu, Don. Manuel E   male  40     0     0
## 136                            Richard, Mr. Emile   male  23     0     0
## 454                      Goldenberg, Mr. Samuel L   male  49     1     0
## 648           Simonius-Blumer, Col. Oberst Alfons   male  56     0     0
## 652                           Doling, Miss. Elsie female  18     0     1
## 880 Potter, Mrs. Thomas Jr (Lily Alexenia Wilson) female  56     0     1
##            Ticket    Fare Cabin Embarked
## 31       PC 17601 27.7208              C
## 136 SC/PARIS 2133 15.0458              C
## 454         17453 89.1042   C92        C
## 648         13213 35.5000   A26        C
## 652        231919 23.0000              S
## 880         11767 83.1583   C50        C
##     PassengerId Survived Pclass                                     Name
## 886         886        0      3     Rice, Mrs. William (Margaret Norton)
## 887         887        0      2                    Montvila, Rev. Juozas
## 888         888        1      1             Graham, Miss. Margaret Edith
## 889         889        0      3 Johnston, Miss. Catherine Helen "Carrie"
## 890         890        1      1                    Behr, Mr. Karl Howell
## 891         891        0      3                      Dooley, Mr. Patrick
##        Sex Age SibSp Parch     Ticket   Fare Cabin Embarked
## 886 female  39     0     5     382652 29.125              Q
## 887   male  27     0     0     211536 13.000              S
## 888 female  19     0     0     112053 30.000   B42        S
## 889 female  NA     1     2 W./C. 6607 23.450              S
## 890   male  26     0     0     111369 30.000  C148        C
## 891   male  32     0     0     370376  7.750              Q
## 'data.frame':    891 obs. of  12 variables:
##  $ PassengerId: int  1 2 3 4 5 6 7 8 9 10 ...
##  $ Survived   : int  0 1 1 1 0 0 0 0 1 1 ...
##  $ Pclass     : int  3 1 3 1 3 3 1 3 3 2 ...
##  $ Name       : chr  "Braund, Mr. Owen Harris" "Cumings, Mrs. John Bradley (Florence Briggs Thayer)" "Heikkinen, Miss. Laina" "Futrelle, Mrs. Jacques Heath (Lily May Peel)" ...
##  $ Sex        : chr  "male" "female" "female" "female" ...
##  $ Age        : num  22 38 26 35 35 NA 54 2 27 14 ...
##  $ SibSp      : int  1 1 0 1 0 0 0 3 0 1 ...
##  $ Parch      : int  0 0 0 0 0 0 0 1 2 0 ...
##  $ Ticket     : chr  "A/5 21171" "PC 17599" "STON/O2. 3101282" "113803" ...
##  $ Fare       : num  7.25 71.28 7.92 53.1 8.05 ...
##  $ Cabin      : chr  "" "C85" "" "C123" ...
##  $ Embarked   : chr  "S" "C" "S" "S" ...
##  - attr(*, "comment")= chr "glbObsTrn"
## NULL
## [1] "Reading file ./data/test.csv..."
## [1] "dimensions of data in ./data/test.csv: 418 rows x 11 cols"
##   PassengerId Pclass                                         Name    Sex
## 1         892      3                             Kelly, Mr. James   male
## 2         893      3             Wilkes, Mrs. James (Ellen Needs) female
## 3         894      2                    Myles, Mr. Thomas Francis   male
## 4         895      3                             Wirz, Mr. Albert   male
## 5         896      3 Hirvonen, Mrs. Alexander (Helga E Lindqvist) female
## 6         897      3                   Svensson, Mr. Johan Cervin   male
##    Age SibSp Parch  Ticket    Fare Cabin Embarked
## 1 34.5     0     0  330911  7.8292              Q
## 2 47.0     1     0  363272  7.0000              S
## 3 62.0     0     0  240276  9.6875              Q
## 4 27.0     0     0  315154  8.6625              S
## 5 22.0     1     1 3101298 12.2875              S
## 6 14.0     0     0    7538  9.2250              S
##     PassengerId Pclass                              Name  Sex  Age SibSp
## 1           892      3                  Kelly, Mr. James male 34.5     0
## 74          965      1   Ovies y Rodriguez, Mr. Servando male 28.5     0
## 162        1053      3    Touma, Master. Georges Youssef male  7.0     1
## 164        1055      3                Pearce, Mr. Ernest male   NA     0
## 167        1058      1                Brandeis, Mr. Emil male 48.0     0
## 193        1084      3 van Billiard, Master. Walter John male 11.5     1
##     Parch   Ticket    Fare Cabin Embarked
## 1       0   330911  7.8292              Q
## 74      0 PC 17562 27.7208   D43        C
## 162     1     2650 15.2458              C
## 164     0   343271  7.0000              S
## 167     0 PC 17591 50.4958   B10        C
## 193     1 A/5. 851 14.5000              S
##     PassengerId Pclass                           Name    Sex  Age SibSp
## 413        1304      3 Henriksson, Miss. Jenny Lovisa female 28.0     0
## 414        1305      3             Spector, Mr. Woolf   male   NA     0
## 415        1306      1   Oliva y Ocana, Dona. Fermina female 39.0     0
## 416        1307      3   Saether, Mr. Simon Sivertsen   male 38.5     0
## 417        1308      3            Ware, Mr. Frederick   male   NA     0
## 418        1309      3       Peter, Master. Michael J   male   NA     1
##     Parch             Ticket     Fare Cabin Embarked
## 413     0             347086   7.7750              S
## 414     0          A.5. 3236   8.0500              S
## 415     0           PC 17758 108.9000  C105        C
## 416     0 SOTON/O.Q. 3101262   7.2500              S
## 417     0             359309   8.0500              S
## 418     1               2668  22.3583              C
## 'data.frame':    418 obs. of  11 variables:
##  $ PassengerId: int  892 893 894 895 896 897 898 899 900 901 ...
##  $ Pclass     : int  3 3 2 3 3 3 3 2 3 3 ...
##  $ Name       : chr  "Kelly, Mr. James" "Wilkes, Mrs. James (Ellen Needs)" "Myles, Mr. Thomas Francis" "Wirz, Mr. Albert" ...
##  $ Sex        : chr  "male" "female" "male" "male" ...
##  $ Age        : num  34.5 47 62 27 22 14 30 26 18 21 ...
##  $ SibSp      : int  0 1 0 0 1 0 0 1 0 2 ...
##  $ Parch      : int  0 0 0 0 1 0 0 1 0 0 ...
##  $ Ticket     : chr  "330911" "363272" "240276" "315154" ...
##  $ Fare       : num  7.83 7 9.69 8.66 12.29 ...
##  $ Cabin      : chr  "" "" "" "" ...
##  $ Embarked   : chr  "Q" "S" "Q" "S" ...
##  - attr(*, "comment")= chr "glbObsNew"
## NULL
## [1] "Creating new feature: .pos..."
## [1] "Creating new feature: Pclass.fctr..."
## [1] "Partition stats:"
## Loading required package: sqldf
## Loading required package: gsubfn
## Loading required package: proto
## Loading required package: RSQLite
## Loading required package: DBI
## Loading required package: tcltk
##   Survived  .src  .n
## 1        0 Train 549
## 2       NA  Test 418
## 3        1 Train 342
##   Survived  .src  .n
## 1        0 Train 549
## 2       NA  Test 418
## 3        1 Train 342
## Loading required package: RColorBrewer

##    .src  .n
## 1 Train 891
## 2  Test 418
## Loading required package: lazyeval
## Loading required package: gdata
## gdata: read.xls support for 'XLS' (Excel 97-2004) files ENABLED.
## 
## gdata: read.xls support for 'XLSX' (Excel 2007+) files ENABLED.
## 
## Attaching package: 'gdata'
## The following objects are masked from 'package:dplyr':
## 
##     combine, first, last
## The following object is masked from 'package:stats':
## 
##     nobs
## The following object is masked from 'package:utils':
## 
##     object.size
## [1] "Found 0 duplicates by all features:"
## NULL
##          label step_major step_minor label_minor    bgn    end elapsed
## 1  import.data          1          0           0  9.263 15.491   6.228
## 2 inspect.data          2          0           0 15.492     NA      NA

Step 2.0: inspect data

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 418 rows containing non-finite values (stat_bin).
## Loading required package: reshape2

##       Survived.0 Survived.1 Survived.NA
## Test          NA         NA         418
## Train        549        342          NA
##       Survived.0 Survived.1 Survived.NA
## Test          NA         NA           1
## Train  0.6161616  0.3838384          NA
## [1] "numeric data missing in glbObsAll: "
## Survived      Age     Fare 
##      418      263        1 
## [1] "numeric data w/ 0s in glbObsAll: "
## Survived    SibSp    Parch     Fare 
##      549      891     1002       17 
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
##     Name      Sex   Ticket    Cabin Embarked 
##        0        0        0     1014        2
##   Survived Survived.fctr  .n
## 1        0             N 549
## 2       NA          <NA> 418
## 3        1             Y 342
## Warning: Removed 1 rows containing missing values (position_stack).

##       Survived.fctr.N Survived.fctr.Y Survived.fctr.NA
## Test               NA              NA              418
## Train             549             342               NA
##       Survived.fctr.N Survived.fctr.Y Survived.fctr.NA
## Test               NA              NA                1
## Train       0.6161616       0.3838384               NA

##          label step_major step_minor label_minor    bgn    end elapsed
## 2 inspect.data          2          0           0 15.492 22.708   7.216
## 3   scrub.data          2          1           1 22.709     NA      NA

Step 2.1: scrub data

## [1] "numeric data missing in glbObsAll: "
##      Survived           Age          Fare Survived.fctr 
##           418           263             1           418 
## [1] "numeric data w/ 0s in glbObsAll: "
## Survived    SibSp    Parch     Fare 
##      549      891     1002       17 
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
##     Name      Sex   Ticket    Cabin Embarked 
##        0        0        0     1014        2
##            label step_major step_minor label_minor    bgn    end elapsed
## 3     scrub.data          2          1           1 22.709 24.484   1.776
## 4 transform.data          2          2           2 24.485     NA      NA

Step 2.2: transform data

##              label step_major step_minor label_minor    bgn    end elapsed
## 4   transform.data          2          2           2 24.485 24.525   0.041
## 5 extract.features          3          0           0 24.526     NA      NA

Step 3.0: extract features

##                       label step_major step_minor label_minor    bgn
## 5          extract.features          3          0           0 24.526
## 6 extract.features.datetime          3          1           1 24.547
##      end elapsed
## 5 24.546    0.02
## 6     NA      NA

Step 3.1: extract features datetime

##                           label step_major step_minor label_minor    bgn
## 1 extract.features.datetime.bgn          1          0           0 24.573
##   end elapsed
## 1  NA      NA
##                       label step_major step_minor label_minor    bgn
## 6 extract.features.datetime          3          1           1 24.547
## 7    extract.features.image          3          2           2 24.583
##      end elapsed
## 6 24.582   0.035
## 7     NA      NA

Step 3.2: extract features image

```{r extract.features.image, cache=FALSE, echo=FALSE, fig.height=5, fig.width=5, eval=myevlChunk(glbChunks, glbOut$pfx)}

##                        label step_major step_minor label_minor    bgn end
## 1 extract.features.image.bgn          1          0           0 24.616  NA
##   elapsed
## 1      NA
##                        label step_major step_minor label_minor    bgn
## 1 extract.features.image.bgn          1          0           0 24.616
## 2 extract.features.image.end          2          0           0 24.626
##      end elapsed
## 1 24.626    0.01
## 2     NA      NA
##                        label step_major step_minor label_minor    bgn
## 1 extract.features.image.bgn          1          0           0 24.616
## 2 extract.features.image.end          2          0           0 24.626
##      end elapsed
## 1 24.626    0.01
## 2     NA      NA
##                    label step_major step_minor label_minor    bgn    end
## 7 extract.features.image          3          2           2 24.583 24.637
## 8 extract.features.price          3          3           3 24.637     NA
##   elapsed
## 7   0.054
## 8      NA

Step 3.3: extract features price

##                        label step_major step_minor label_minor    bgn end
## 1 extract.features.price.bgn          1          0           0 24.664  NA
##   elapsed
## 1      NA
##                    label step_major step_minor label_minor    bgn    end
## 8 extract.features.price          3          3           3 24.637 24.674
## 9  extract.features.text          3          4           4 24.674     NA
##   elapsed
## 8   0.037
## 9      NA

Step 3.4: extract features text

##                       label step_major step_minor label_minor    bgn end
## 1 extract.features.text.bgn          1          0           0 24.718  NA
##   elapsed
## 1      NA
##                      label step_major step_minor label_minor    bgn    end
## 9    extract.features.text          3          4           4 24.674 24.727
## 10 extract.features.string          3          5           5 24.732     NA
##    elapsed
## 9    0.053
## 10      NA

Step 3.5: extract features string

##                         label step_major step_minor label_minor    bgn end
## 1 extract.features.string.bgn          1          0           0 24.765  NA
##   elapsed
## 1      NA
##                                       label step_major step_minor
## 1               extract.features.string.bgn          1          0
## 2 extract.features.stringfactorize.str.vars          2          0
##   label_minor    bgn    end elapsed
## 1           0 24.765 24.775    0.01
## 2           0 24.775     NA      NA
##       Name        Sex     Ticket      Cabin   Embarked       .src 
##     "Name"      "Sex"   "Ticket"    "Cabin" "Embarked"     ".src"
##                      label step_major step_minor label_minor    bgn    end
## 10 extract.features.string          3          5           5 24.732 24.788
## 11    extract.features.end          3          6           6 24.789     NA
##    elapsed
## 10   0.056
## 11      NA

Step 3.6: extract features end

## time trans    "bgn " "fit.data.training.all " "predict.data.new " "end " 
## 0.0000   multiple enabled transitions:  data.training.all data.new model.selected    firing:  data.training.all 
## 1.0000    1   2 1 0 0 
## 1.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction   firing:  data.new 
## 2.0000    2   1 1 1 0

##                   label step_major step_minor label_minor    bgn    end
## 11 extract.features.end          3          6           6 24.789 25.728
## 12  manage.missing.data          4          0           0 25.728     NA
##    elapsed
## 11   0.939
## 12      NA

Step 4.0: manage missing data

## [1] "numeric data missing in glbObsAll: "
##      Survived           Age          Fare Survived.fctr 
##           418           263             1           418 
## [1] "numeric data w/ 0s in glbObsAll: "
## Survived    SibSp    Parch     Fare 
##      549      891     1002       17 
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
##     Name      Sex   Ticket    Cabin Embarked 
##        0        0        0     1014        2
## [1] "numeric data missing in glbObsAll: "
##      Survived           Age          Fare Survived.fctr 
##           418           263             1           418 
## [1] "numeric data w/ 0s in glbObsAll: "
## Survived    SibSp    Parch     Fare 
##      549      891     1002       17 
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
##     Name      Sex   Ticket    Cabin Embarked 
##        0        0        0     1014        2
##                  label step_major step_minor label_minor    bgn    end
## 12 manage.missing.data          4          0           0 25.728 25.995
## 13        cluster.data          5          0           0 25.996     NA
##    elapsed
## 12   0.267
## 13      NA

Step 5.0: cluster data

##                      label step_major step_minor label_minor    bgn    end
## 13            cluster.data          5          0           0 25.996 26.043
## 14 partition.data.training          6          0           0 26.043     NA
##    elapsed
## 13   0.047
## 14      NA

Step 6.0: partition data training

## [1] "partition.data.training chunk: setup: elapsed: 0.00 secs"
## [1] "partition.data.training chunk: strata_mtrx complete: elapsed: 0.09 secs"
## [1] "partition.data.training chunk: obs_freq_df complete: elapsed: 0.09 secs"
## Loading required package: sampling
## 
## Attaching package: 'sampling'
## The following objects are masked from 'package:survival':
## 
##     cluster, strata
## The following object is masked from 'package:caret':
## 
##     cluster
## [1] "partition.data.training chunk: Fit/OOB partition complete: elapsed: 0.25 secs"
##     Survived.0 Survived.1 Survived.NA
##             NA         NA         418
## Fit        313        197          NA
## OOB        236        145          NA
##     Survived.0 Survived.1 Survived.NA
##             NA         NA           1
## Fit  0.6137255  0.3862745          NA
## OOB  0.6194226  0.3805774          NA
##   Pclass.fctr .n.Fit .n.OOB .n.Tst .freqRatio.Fit .freqRatio.OOB
## 3           3    284    207    218      0.5568627      0.5433071
## 1           1    130     86    107      0.2549020      0.2257218
## 2           2     96     88     93      0.1882353      0.2309711
##   .freqRatio.Tst
## 3      0.5215311
## 1      0.2559809
## 2      0.2224880
## [1] "glbObsAll: "
## [1] 1309   18
## [1] "glbObsTrn: "
## [1] 891  18
## [1] "glbObsFit: "
## [1] 510  17
## [1] "glbObsOOB: "
## [1] 381  17
## [1] "glbObsNew: "
## [1] 418  17
## [1] "partition.data.training chunk: teardown: elapsed: 0.40 secs"
##                      label step_major step_minor label_minor    bgn    end
## 14 partition.data.training          6          0           0 26.043 26.504
## 15         select.features          7          0           0 26.504     NA
##    elapsed
## 14   0.461
## 15      NA

Step 7.0: select features

##                    cor.y exclude.as.feat   cor.y.abs cor.high.X freqRatio
## Survived     1.000000000               1 1.000000000         NA  1.605263
## Fare         0.257306522               1 0.257306522         NA  1.023810
## Parch        0.081629407               1 0.081629407         NA  5.745763
## .pos        -0.005006661               0 0.005006661         NA  1.000000
## PassengerId -0.005006661               0 0.005006661         NA  1.000000
## SibSp       -0.035322499               1 0.035322499         NA  2.909091
## .rnorm      -0.050404605               0 0.050404605         NA  1.000000
## Age         -0.077221095               1 0.077221095         NA  1.111111
## Pclass      -0.338481036               1 0.338481036         NA  2.273148
## Pclass.fctr -0.338481036               0 0.338481036         NA  2.273148
##             percentUnique zeroVar   nzv is.cor.y.abs.low
## Survived        0.2244669   FALSE FALSE            FALSE
## Fare           27.8338945   FALSE FALSE            FALSE
## Parch           0.7856341   FALSE FALSE            FALSE
## .pos          100.0000000   FALSE FALSE             TRUE
## PassengerId   100.0000000   FALSE FALSE             TRUE
## SibSp           0.7856341   FALSE FALSE             TRUE
## .rnorm        100.0000000   FALSE FALSE            FALSE
## Age             9.8765432   FALSE FALSE            FALSE
## Pclass          0.3367003   FALSE FALSE            FALSE
## Pclass.fctr     0.3367003   FALSE FALSE            FALSE
## Warning in myplot_scatter(plt_feats_df, "percentUnique", "freqRatio",
## colorcol_name = "nzv", : converting nzv to class:factor
## Warning: Removed 4 rows containing missing values (geom_point).

## Warning: Removed 4 rows containing missing values (geom_point).

## Warning: Removed 4 rows containing missing values (geom_point).

## [1] cor.y            exclude.as.feat  cor.y.abs        cor.high.X      
## [5] freqRatio        percentUnique    zeroVar          nzv             
## [9] is.cor.y.abs.low
## <0 rows> (or 0-length row.names)

## [1] "numeric data missing in glbObsAll: "
##      Survived           Age          Fare Survived.fctr 
##           418           263             1           418 
## [1] "numeric data w/ 0s in glbObsAll: "
## Survived    SibSp    Parch     Fare 
##      549      891     1002       17 
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
##     Name      Sex   Ticket    Cabin Embarked     .lcn 
##        0        0        0     1014        2      418
## [1] "glb_feats_df:"
## [1] 10 12
##                          id exclude.as.feat rsp_var
## Survived.fctr Survived.fctr            TRUE    TRUE
##                          id        cor.y exclude.as.feat   cor.y.abs
## Survived           Survived  1.000000000            TRUE 1.000000000
## PassengerId     PassengerId -0.005006661           FALSE 0.005006661
## Survived.fctr Survived.fctr           NA            TRUE          NA
##               cor.high.X freqRatio percentUnique zeroVar   nzv
## Survived              NA  1.605263     0.2244669   FALSE FALSE
## PassengerId           NA  1.000000   100.0000000   FALSE FALSE
## Survived.fctr         NA        NA            NA      NA    NA
##               is.cor.y.abs.low interaction.feat shapiro.test.p.value
## Survived                 FALSE               NA                   NA
## PassengerId               TRUE               NA         6.308054e-16
## Survived.fctr               NA               NA                   NA
##               rsp_var_raw id_var rsp_var
## Survived             TRUE     NA      NA
## PassengerId         FALSE   TRUE      NA
## Survived.fctr          NA     NA    TRUE
## [1] "glb_feats_df vs. glbObsAll: "
## character(0)
## [1] "glbObsAll vs. glb_feats_df: "
## character(0)
##              label step_major step_minor label_minor    bgn    end elapsed
## 15 select.features          7          0           0 26.504 27.978   1.474
## 16      fit.models          8          0           0 27.978     NA      NA

Step 8.0: fit models

fit.models_0_chunk_df <- myadd_chunk(NULL, "fit.models_0_bgn", label.minor = "setup")
##              label step_major step_minor label_minor    bgn end elapsed
## 1 fit.models_0_bgn          1          0       setup 28.456  NA      NA
# load(paste0(glbOut$pfx, "dsk.RData"))

get_model_sel_frmla <- function() {
    model_evl_terms <- c(NULL)
    # min.aic.fit might not be avl
    lclMdlEvlCriteria <- 
        glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)]
    for (metric in lclMdlEvlCriteria)
        model_evl_terms <- c(model_evl_terms, 
                             ifelse(length(grep("max", metric)) > 0, "-", "+"), metric)
    if (glb_is_classification && glb_is_binomial)
        model_evl_terms <- c(model_evl_terms, "-", "opt.prob.threshold.OOB")
    model_sel_frmla <- as.formula(paste(c("~ ", model_evl_terms), collapse = " "))
    return(model_sel_frmla)
}

get_dsp_models_df <- function() {
    dsp_models_cols <- c("id", 
                    glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
                    grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE)) 
    dsp_models_df <- 
        #orderBy(get_model_sel_frmla(), glb_models_df)[, c("id", glbMdlMetricsEval)]
        orderBy(get_model_sel_frmla(), glb_models_df)[, dsp_models_cols]    
    nCvMdl <- sapply(glb_models_lst, function(mdl) nrow(mdl$results))
    nParams <- sapply(glb_models_lst, function(mdl) ifelse(mdl$method == "custom", 0, 
        nrow(subset(modelLookup(mdl$method), parameter != "parameter"))))
    
#     nCvMdl <- nCvMdl[names(nCvMdl) != "avNNet"]
#     nParams <- nParams[names(nParams) != "avNNet"]    
    
    if (length(cvMdlProblems <- nCvMdl[nCvMdl <= nParams]) > 0) {
        print("Cross Validation issues:")
        warning("Cross Validation issues:")        
        print(cvMdlProblems)
    }
    
    pltMdls <- setdiff(names(nCvMdl), names(cvMdlProblems))
    pltMdls <- setdiff(pltMdls, names(nParams[nParams == 0]))
    
    # length(pltMdls) == 21
    png(paste0(glbOut$pfx, "bestTune.png"), width = 480 * 2, height = 480 * 4)
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(ceiling(length(pltMdls) / 2.0), 2)))
    pltIx <- 1
    for (mdlId in pltMdls) {
        print(ggplot(glb_models_lst[[mdlId]], highBestTune = TRUE) + labs(title = mdlId),   
              vp = viewport(layout.pos.row = ceiling(pltIx / 2.0), 
                            layout.pos.col = ((pltIx - 1) %% 2) + 1))  
        pltIx <- pltIx + 1
    }
    dev.off()

    if (all(row.names(dsp_models_df) != dsp_models_df$id))
        row.names(dsp_models_df) <- dsp_models_df$id
    return(dsp_models_df)
}
#get_dsp_models_df()

if (glb_is_classification && glb_is_binomial && 
        (length(unique(glbObsFit[, glb_rsp_var])) < 2))
    stop("glbObsFit$", glb_rsp_var, ": contains less than 2 unique values: ",
         paste0(unique(glbObsFit[, glb_rsp_var]), collapse=", "))

max_cor_y_x_vars <- orderBy(~ -cor.y.abs, 
        subset(glb_feats_df, (exclude.as.feat == 0) & !nzv & !is.cor.y.abs.low & 
                                is.na(cor.high.X)))[1:2, "id"]
max_cor_y_x_vars <- max_cor_y_x_vars[!is.na(max_cor_y_x_vars)]
if (length(max_cor_y_x_vars) < 2)
    max_cor_y_x_vars <- union(max_cor_y_x_vars, ".pos")

if (!is.null(glb_Baseline_mdl_var)) {
    if ((max_cor_y_x_vars[1] != glb_Baseline_mdl_var) & 
        (glb_feats_df[glb_feats_df$id == max_cor_y_x_vars[1], "cor.y.abs"] > 
         glb_feats_df[glb_feats_df$id == glb_Baseline_mdl_var, "cor.y.abs"]))
        stop(max_cor_y_x_vars[1], " has a higher correlation with ", glb_rsp_var, 
             " than the Baseline var: ", glb_Baseline_mdl_var)
}

glb_model_type <- ifelse(glb_is_regression, "regression", "classification")
    
# Model specs
c("id.prefix", "method", "type",
  # trainControl params
  "preProc.method", "cv.n.folds", "cv.n.repeats", "summary.fn",
  # train params
  "metric", "metric.maximize", "tune.df")
##  [1] "id.prefix"       "method"          "type"           
##  [4] "preProc.method"  "cv.n.folds"      "cv.n.repeats"   
##  [7] "summary.fn"      "metric"          "metric.maximize"
## [10] "tune.df"
# Baseline
if (!is.null(glb_Baseline_mdl_var)) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                            paste0("fit.models_0_", "Baseline"), major.inc = FALSE,
                                    label.minor = "mybaseln_classfr")
    ret_lst <- myfit_mdl(mdl_id="Baseline", 
                         model_method="mybaseln_classfr",
                        indep_vars_vctr=glb_Baseline_mdl_var,
                        rsp_var=glb_rsp_var,
                        fit_df=glbObsFit, OOB_df=glbObsOOB)
}    

# Most Frequent Outcome "MFO" model: mean(y) for regression
#   Not using caret's nullModel since model stats not avl
#   Cannot use rpart for multinomial classification since it predicts non-MFO
if (glb_is_classification) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                                paste0("fit.models_0_", "MFO"), major.inc = FALSE,
                                        label.minor = "myMFO_classfr")

    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "MFO", type = glb_model_type, trainControl.method = "none",
        train.method = ifelse(glb_is_regression, "lm", "myMFO_classfr"))),
                            indep_vars = ".rnorm", rsp_var = glb_rsp_var,
                            fit_df = glbObsFit, OOB_df = glbObsOOB)

        # "random" model - only for classification; 
        #   none needed for regression since it is same as MFO
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                                paste0("fit.models_0_", "Random"), major.inc = FALSE,
                                        label.minor = "myrandom_classfr")

#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)    
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Random", type = glb_model_type, trainControl.method = "none",
        train.method = "myrandom_classfr")),
                        indep_vars = ".rnorm", rsp_var = glb_rsp_var,
                        fit_df = glbObsFit, OOB_df = glbObsOOB)
}
##              label step_major step_minor   label_minor    bgn    end
## 1 fit.models_0_bgn          1          0         setup 28.456 28.491
## 2 fit.models_0_MFO          1          1 myMFO_classfr 28.491     NA
##   elapsed
## 1   0.035
## 2      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: MFO###myMFO_classfr"
## [1] "    indep_vars: .rnorm"
## [1] "myfit_mdl: setup complete: 0.728000 secs"
## Fitting parameter = none on full training set
## [1] "in MFO.Classifier$fit"
## [1] "unique.vals:"
## [1] N Y
## Levels: N Y
## [1] "unique.prob:"
## y
##         N         Y 
## 0.6137255 0.3862745 
## [1] "MFO.val:"
## [1] "N"
## [1] "myfit_mdl: train complete: 1.101000 secs"
##             Length Class      Mode     
## unique.vals 2      factor     numeric  
## unique.prob 2      -none-     numeric  
## MFO.val     1      -none-     character
## x.names     1      -none-     character
## xNames      1      -none-     character
## problemType 1      -none-     character
## tuneValue   1      data.frame list     
## obsLevels   2      -none-     character
## [1] "myfit_mdl: train diagnostics complete: 1.103000 secs"
## Loading required namespace: pROC
## [1] "entr MFO.Classifier$predict"
## [1] "exit MFO.Classifier$predict"
## Loading required package: ROCR
## Loading required package: gplots
## 
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
## 
##     lowess
## [1] "in MFO.Classifier$prob"
##           N         Y
## 1 0.6137255 0.3862745
## 2 0.6137255 0.3862745
## 3 0.6137255 0.3862745
## 4 0.6137255 0.3862745
## 5 0.6137255 0.3862745
## 6 0.6137255 0.3862745

##          Prediction
## Reference   N   Y
##         N   0 313
##         Y   0 197
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   3.862745e-01   0.000000e+00   3.438031e-01   4.300722e-01   6.137255e-01 
## AccuracyPValue  McnemarPValue 
##   1.000000e+00   1.320342e-69 
## [1] "entr MFO.Classifier$predict"
## [1] "exit MFO.Classifier$predict"
## [1] "in MFO.Classifier$prob"
##           N         Y
## 1 0.6137255 0.3862745
## 2 0.6137255 0.3862745
## 3 0.6137255 0.3862745
## 4 0.6137255 0.3862745
## 5 0.6137255 0.3862745
## 6 0.6137255 0.3862745

##          Prediction
## Reference   N   Y
##         N   0 236
##         Y   0 145
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   3.805774e-01   0.000000e+00   3.316072e-01   4.314187e-01   6.194226e-01 
## AccuracyPValue  McnemarPValue 
##   1.000000e+00   7.982101e-53 
## [1] "myfit_mdl: predict complete: 2.941000 secs"
##                    id  feats max.nTuningRuns min.elapsedtime.everything
## 1 MFO###myMFO_classfr .rnorm               0                      0.365
##   min.elapsedtime.final max.AUCpROC.fit max.Sens.fit max.Spec.fit
## 1                 0.004             0.5            1            0
##   max.AUCROCR.fit opt.prob.threshold.fit max.f.score.fit max.Accuracy.fit
## 1             0.5                    0.3       0.5572843        0.3862745
##   max.AccuracyLower.fit max.AccuracyUpper.fit max.Kappa.fit
## 1             0.3438031             0.4300722             0
##   max.AUCpROC.OOB max.Sens.OOB max.Spec.OOB max.AUCROCR.OOB
## 1             0.5            1            0             0.5
##   opt.prob.threshold.OOB max.f.score.OOB max.Accuracy.OOB
## 1                    0.3       0.5513308        0.3805774
##   max.AccuracyLower.OOB max.AccuracyUpper.OOB max.Kappa.OOB
## 1             0.3316072             0.4314187             0
## [1] "myfit_mdl: exit: 2.950000 secs"
##                 label step_major step_minor      label_minor    bgn    end
## 2    fit.models_0_MFO          1          1    myMFO_classfr 28.491 31.448
## 3 fit.models_0_Random          1          2 myrandom_classfr 31.448     NA
##   elapsed
## 2   2.957
## 3      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Random###myrandom_classfr"
## [1] "    indep_vars: .rnorm"
## [1] "myfit_mdl: setup complete: 0.449000 secs"
## Fitting parameter = none on full training set
## [1] "myfit_mdl: train complete: 0.721000 secs"
##             Length Class      Mode     
## unique.vals 2      factor     numeric  
## unique.prob 2      table      numeric  
## xNames      1      -none-     character
## problemType 1      -none-     character
## tuneValue   1      data.frame list     
## obsLevels   2      -none-     character
## [1] "myfit_mdl: train diagnostics complete: 0.722000 secs"
## [1] "in Random.Classifier$prob"

##          Prediction
## Reference   N   Y
##         N   0 313
##         Y   0 197
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   3.862745e-01   0.000000e+00   3.438031e-01   4.300722e-01   6.137255e-01 
## AccuracyPValue  McnemarPValue 
##   1.000000e+00   1.320342e-69 
## [1] "in Random.Classifier$prob"

##          Prediction
## Reference   N   Y
##         N   0 236
##         Y   0 145
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   3.805774e-01   0.000000e+00   3.316072e-01   4.314187e-01   6.194226e-01 
## AccuracyPValue  McnemarPValue 
##   1.000000e+00   7.982101e-53 
## [1] "myfit_mdl: predict complete: 2.542000 secs"
##                          id  feats max.nTuningRuns
## 1 Random###myrandom_classfr .rnorm               0
##   min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1                      0.268                 0.002       0.5093819
##   max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1    0.5974441    0.4213198       0.5620084                    0.3
##   max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1       0.5572843        0.3862745             0.3438031
##   max.AccuracyUpper.fit max.Kappa.fit max.AUCpROC.OOB max.Sens.OOB
## 1             0.4300722             0       0.4867621    0.6355932
##   max.Spec.OOB max.AUCROCR.OOB opt.prob.threshold.OOB max.f.score.OOB
## 1     0.337931        0.445675                    0.3       0.5513308
##   max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1        0.3805774             0.3316072             0.4314187
##   max.Kappa.OOB
## 1             0
## [1] "myfit_mdl: exit: 2.554000 secs"
# Max.cor.Y
#   Check impact of cv
#       rpart is not a good candidate since caret does not optimize cp (only tuning parameter of rpart) well
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                        paste0("fit.models_0_", "Max.cor.Y.rcv.*X*"), major.inc = FALSE,
                                    label.minor = "glmnet")
##                            label step_major step_minor      label_minor
## 3            fit.models_0_Random          1          2 myrandom_classfr
## 4 fit.models_0_Max.cor.Y.rcv.*X*          1          3           glmnet
##      bgn    end elapsed
## 3 31.448 34.014   2.566
## 4 34.014     NA      NA
ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
    id.prefix="Max.cor.Y.rcv.1X1", type=glb_model_type, trainControl.method="none",
    train.method="glmnet")),
                    indep_vars=max_cor_y_x_vars, rsp_var=glb_rsp_var, 
                    fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Max.cor.Y.rcv.1X1###glmnet"
## [1] "    indep_vars: Pclass.fctr,.rnorm"
## [1] "myfit_mdl: setup complete: 0.736000 secs"
## Loading required package: glmnet
## Loading required package: Matrix
## Loaded glmnet 2.0-2
## Fitting alpha = 0.1, lambda = 0.00392 on full training set
## [1] "myfit_mdl: train complete: 1.451000 secs"

##             Length Class      Mode     
## a0           73    -none-     numeric  
## beta        219    dgCMatrix  S4       
## df           73    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       73    -none-     numeric  
## dev.ratio    73    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## classnames    2    -none-     character
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames        3    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     2    -none-     character
## [1] "min lambda > lambdaOpt:"
##  (Intercept)       .rnorm Pclass.fctr2 Pclass.fctr3 
##   0.75495718  -0.07649186  -0.77774467  -2.05101190 
## [1] "max lambda < lambdaOpt:"
##  (Intercept)       .rnorm Pclass.fctr2 Pclass.fctr3 
##   0.75922519  -0.07675417  -0.78310177  -2.05725407 
## [1] "myfit_mdl: train diagnostics complete: 1.558000 secs"

##          Prediction
## Reference   N   Y
##         N 224  89
##         Y  60 137
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   7.078431e-01   4.001705e-01   6.662695e-01   7.469880e-01   6.137255e-01 
## AccuracyPValue  McnemarPValue 
##   5.482557e-06   2.179915e-02

##          Prediction
## Reference   N   Y
##         N  19 217
##         Y   7 138
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   4.120735e-01   2.519703e-02   3.621900e-01   4.633340e-01   6.194226e-01 
## AccuracyPValue  McnemarPValue 
##   1.000000e+00   2.570616e-44 
## [1] "myfit_mdl: predict complete: 3.663000 secs"
##                           id              feats max.nTuningRuns
## 1 Max.cor.Y.rcv.1X1###glmnet Pclass.fctr,.rnorm               0
##   min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1                       0.71                 0.016       0.6970614
##   max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1    0.8306709    0.5634518       0.7254018                    0.4
##   max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1       0.6477541        0.7078431             0.6662695
##   max.AccuracyUpper.fit max.Kappa.fit max.AUCpROC.OOB max.Sens.OOB
## 1              0.746988     0.4001705       0.6118498    0.7754237
##   max.Spec.OOB max.AUCROCR.OOB opt.prob.threshold.OOB max.f.score.OOB
## 1    0.4482759       0.6326125                    0.2           0.552
##   max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1        0.4120735               0.36219              0.463334
##   max.Kappa.OOB
## 1    0.02519703
## [1] "myfit_mdl: exit: 3.676000 secs"
if (glbMdlCheckRcv) {
    # rcv_n_folds == 1 & rcv_n_repeats > 1 crashes
    for (rcv_n_folds in seq(3, glb_rcv_n_folds + 2, 2))
        for (rcv_n_repeats in seq(1, glb_rcv_n_repeats + 2, 2)) {
            
            # Experiment specific code to avoid caret crash
    #         lcl_tune_models_df <- rbind(data.frame()
    #                             ,data.frame(method = "glmnet", parameter = "alpha", 
    #                                         vals = "0.100 0.325 0.550 0.775 1.000")
    #                             ,data.frame(method = "glmnet", parameter = "lambda",
    #                                         vals = "9.342e-02")    
    #                                     )
            
            ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst =
                list(
                id.prefix = paste0("Max.cor.Y.rcv.", rcv_n_folds, "X", rcv_n_repeats), 
                type = glb_model_type, 
    # tune.df = lcl_tune_models_df,            
                trainControl.method = "repeatedcv",
                trainControl.number = rcv_n_folds, 
                trainControl.repeats = rcv_n_repeats,
                trainControl.classProbs = glb_is_classification,
                trainControl.summaryFunction = glbMdlMetricSummaryFn,
                train.method = "glmnet", train.metric = glbMdlMetricSummary, 
                train.maximize = glbMdlMetricMaximize)),
                                indep_vars = max_cor_y_x_vars, rsp_var = glb_rsp_var, 
                                fit_df = glbObsFit, OOB_df = glbObsOOB)
        }
    # Add parallel coordinates graph of glb_models_df[, glbMdlMetricsEval] to evaluate cv parameters
    tmp_models_cols <- c("id", "max.nTuningRuns",
                        glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
                        grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE)) 
    print(myplot_parcoord(obs_df = subset(glb_models_df, 
                                          grepl("Max.cor.Y.rcv.", id, fixed = TRUE), 
                                            select = -feats)[, tmp_models_cols],
                          id_var = "id"))
}
        
# Useful for stacking decisions
# fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
#                     paste0("fit.models_0_", "Max.cor.Y[rcv.1X1.cp.0|]"), major.inc = FALSE,
#                                     label.minor = "rpart")
# 
# ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
#     id.prefix = "Max.cor.Y.rcv.1X1.cp.0", type = glb_model_type, trainControl.method = "none",
#     train.method = "rpart",
#     tune.df=data.frame(method="rpart", parameter="cp", min=0.0, max=0.0, by=0.1))),
#                     indep_vars=max_cor_y_x_vars, rsp_var=glb_rsp_var, 
#                     fit_df=glbObsFit, OOB_df=glbObsOOB)

#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)
# if (glb_is_regression || glb_is_binomial) # For multinomials this model will be run next by default
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                        id.prefix = "Max.cor.Y", 
                        type = glb_model_type, trainControl.method = "repeatedcv",
                        trainControl.number = glb_rcv_n_folds, 
                        trainControl.repeats = glb_rcv_n_repeats,
                        trainControl.classProbs = glb_is_classification,
                        trainControl.summaryFunction = glbMdlMetricSummaryFn,
                        trainControl.allowParallel = glbMdlAllowParallel,                        
                        train.metric = glbMdlMetricSummary, 
                        train.maximize = glbMdlMetricMaximize,    
                        train.method = "rpart")),
                    indep_vars = max_cor_y_x_vars, rsp_var = glb_rsp_var, 
                    fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Max.cor.Y##rcv#rpart"
## [1] "    indep_vars: Pclass.fctr,.rnorm"
## [1] "myfit_mdl: setup complete: 0.732000 secs"
## Loading required package: rpart
## Aggregating results
## Selecting tuning parameters
## Fitting cp = 0.0102 on full training set
## [1] "myfit_mdl: train complete: 2.365000 secs"
## Loading required package: rpart.plot

## Call:
## rpart(formula = .outcome ~ ., control = list(minsplit = 20, minbucket = 7, 
##     cp = 0, maxcompete = 4, maxsurrogate = 5, usesurrogate = 2, 
##     surrogatestyle = 0, maxdepth = 30, xval = 0))
##   n= 510 
## 
##           CP nsplit rel error
## 1 0.24365482      0 1.0000000
## 2 0.03045685      1 0.7563452
## 3 0.01015228      3 0.6954315
## 
## Variable importance
## Pclass.fctr3 Pclass.fctr2       .rnorm 
##           60           32            8 
## 
## Node number 1: 510 observations,    complexity param=0.2436548
##   predicted class=N  expected loss=0.3862745  P(node) =1
##     class counts:   313   197
##    probabilities: 0.614 0.386 
##   left son=2 (284 obs) right son=3 (226 obs)
##   Primary splits:
##       Pclass.fctr3 < 0.5        to the right, improve=39.257300, (0 missing)
##       Pclass.fctr2 < 0.5        to the left,  improve= 2.524329, (0 missing)
##       .rnorm       < -0.9164055 to the right, improve= 2.375037, (0 missing)
##   Surrogate splits:
##       Pclass.fctr2 < 0.5        to the left,  agree=0.745, adj=0.425, (0 split)
##       .rnorm       < -1.083251  to the right, agree=0.582, adj=0.058, (0 split)
## 
## Node number 2: 284 observations
##   predicted class=N  expected loss=0.2112676  P(node) =0.5568627
##     class counts:   224    60
##    probabilities: 0.789 0.211 
## 
## Node number 3: 226 observations,    complexity param=0.03045685
##   predicted class=Y  expected loss=0.3938053  P(node) =0.4431373
##     class counts:    89   137
##    probabilities: 0.394 0.606 
##   left son=6 (96 obs) right son=7 (130 obs)
##   Primary splits:
##       Pclass.fctr2 < 0.5        to the right, improve=4.538873, (0 missing)
##       .rnorm       < -0.2279056 to the right, improve=2.717757, (0 missing)
##   Surrogate splits:
##       .rnorm < -2.173493  to the left,  agree=0.593, adj=0.042, (0 split)
## 
## Node number 6: 96 observations,    complexity param=0.03045685
##   predicted class=N  expected loss=0.4895833  P(node) =0.1882353
##     class counts:    49    47
##    probabilities: 0.510 0.490 
##   left son=12 (40 obs) right son=13 (56 obs)
##   Primary splits:
##       .rnorm < 0.4183561  to the right, improve=2.672024, (0 missing)
## 
## Node number 7: 130 observations
##   predicted class=Y  expected loss=0.3076923  P(node) =0.254902
##     class counts:    40    90
##    probabilities: 0.308 0.692 
## 
## Node number 12: 40 observations
##   predicted class=N  expected loss=0.35  P(node) =0.07843137
##     class counts:    26    14
##    probabilities: 0.650 0.350 
## 
## Node number 13: 56 observations
##   predicted class=Y  expected loss=0.4107143  P(node) =0.1098039
##     class counts:    23    33
##    probabilities: 0.411 0.589 
## 
## n= 510 
## 
## node), split, n, loss, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 510 197 N (0.6137255 0.3862745)  
##    2) Pclass.fctr3>=0.5 284  60 N (0.7887324 0.2112676) *
##    3) Pclass.fctr3< 0.5 226  89 Y (0.3938053 0.6061947)  
##      6) Pclass.fctr2>=0.5 96  47 N (0.5104167 0.4895833)  
##       12) .rnorm>=0.4183561 40  14 N (0.6500000 0.3500000) *
##       13) .rnorm< 0.4183561 56  23 Y (0.4107143 0.5892857) *
##      7) Pclass.fctr2< 0.5 130  40 Y (0.3076923 0.6923077) *
## [1] "myfit_mdl: train diagnostics complete: 3.136000 secs"

##          Prediction
## Reference   N   Y
##         N 224  89
##         Y  60 137
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   7.078431e-01   4.001705e-01   6.662695e-01   7.469880e-01   6.137255e-01 
## AccuracyPValue  McnemarPValue 
##   5.482557e-06   2.179915e-02

##          Prediction
## Reference   N   Y
##         N   0 236
##         Y   0 145
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   3.805774e-01   0.000000e+00   3.316072e-01   4.314187e-01   6.194226e-01 
## AccuracyPValue  McnemarPValue 
##   1.000000e+00   7.982101e-53 
## [1] "myfit_mdl: predict complete: 4.816000 secs"
##                     id              feats max.nTuningRuns
## 1 Max.cor.Y##rcv#rpart Pclass.fctr,.rnorm               5
##   min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1                      1.628                 0.013       0.7115438
##   max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1     0.798722    0.6243655        0.730405                    0.3
##   max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1       0.6477541        0.7078962             0.6662695
##   max.AccuracyUpper.fit max.Kappa.fit max.AUCpROC.OOB max.Sens.OOB
## 1              0.746988     0.3659851       0.6137639    0.7033898
##   max.Spec.OOB max.AUCROCR.OOB opt.prob.threshold.OOB max.f.score.OOB
## 1    0.5241379       0.6225015                    0.2       0.5513308
##   max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1        0.3805774             0.3316072             0.4314187
##   max.Kappa.OOB max.AccuracySD.fit max.KappaSD.fit
## 1             0         0.03483382      0.07002241
## [1] "myfit_mdl: exit: 4.831000 secs"
if ((length(glbFeatsDateTime) > 0) && 
    (sum(grepl(paste(names(glbFeatsDateTime), "\\.day\\.minutes\\.poly\\.", sep = ""),
               names(glbObsAll))) > 0)) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Max.cor.Y.Time.Poly"), major.inc = FALSE,
                                    label.minor = "glmnet")

    indepVars <- c(max_cor_y_x_vars, 
            grep(paste(names(glbFeatsDateTime), "\\.day\\.minutes\\.poly\\.", sep = ""),
                        names(glbObsAll), value = TRUE))
    indepVars <- myadjust_interaction_feats(indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
            id.prefix = "Max.cor.Y.Time.Poly", 
            type = glb_model_type, trainControl.method = "repeatedcv",
            trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method = "glmnet")),
        indep_vars = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

if ((length(glbFeatsDateTime) > 0) && 
    (sum(grepl(paste(names(glbFeatsDateTime), "\\.last[[:digit:]]", sep = ""),
               names(glbObsAll))) > 0)) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Max.cor.Y.Time.Lag"), major.inc = FALSE,
                                    label.minor = "glmnet")

    indepVars <- c(max_cor_y_x_vars, 
            grep(paste(names(glbFeatsDateTime), "\\.last[[:digit:]]", sep = ""),
                        names(glbObsAll), value = TRUE))
    indepVars <- myadjust_interaction_feats(indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Time.Lag", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indep_vars = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

if (length(glbFeatsText) > 0) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Txt.*"), major.inc = FALSE,
                                    label.minor = "glmnet")

    indepVars <- c(max_cor_y_x_vars)
    for (txtFeat in names(glbFeatsText))
        indepVars <- union(indepVars, 
            grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.(?!([T|P]\\.))", sep = ""),
                        names(glbObsAll), perl = TRUE, value = TRUE))
    indepVars <- myadjust_interaction_feats(indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Text.nonTP", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        trainControl.allowParallel = glbMdlAllowParallel,                                
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indep_vars = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)

    indepVars <- c(max_cor_y_x_vars)
    for (txtFeat in names(glbFeatsText))
        indepVars <- union(indepVars, 
            grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.T\\.", sep = ""),
                        names(glbObsAll), perl = TRUE, value = TRUE))
    indepVars <- myadjust_interaction_feats(indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Text.onlyT", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indep_vars = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)

    indepVars <- c(max_cor_y_x_vars)
    for (txtFeat in names(glbFeatsText))
        indepVars <- union(indepVars, 
            grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.P\\.", sep = ""),
                        names(glbObsAll), perl = TRUE, value = TRUE))
    indepVars <- myadjust_interaction_feats(indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Text.onlyP", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        trainControl.allowParallel = glbMdlAllowParallel,        
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indep_vars = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

# Interactions.High.cor.Y
if (length(int_feats <- setdiff(setdiff(unique(glb_feats_df$cor.high.X), NA), 
                                subset(glb_feats_df, nzv)$id)) > 0) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Interact.High.cor.Y"), major.inc = FALSE,
                                    label.minor = "glmnet")

    ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
        id.prefix="Interact.High.cor.Y", 
        type=glb_model_type, trainControl.method="repeatedcv",
        trainControl.number=glb_rcv_n_folds, trainControl.repeats=glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        trainControl.allowParallel = glbMdlAllowParallel,
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method="glmnet")),
        indep_vars=c(max_cor_y_x_vars, paste(max_cor_y_x_vars[1], int_feats, sep=":")),
        rsp_var=glb_rsp_var, 
        fit_df=glbObsFit, OOB_df=glbObsOOB)
}    

# Low.cor.X
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                        paste0("fit.models_0_", "Low.cor.X"), major.inc = FALSE,
                                     label.minor = "glmnet")
##                            label step_major step_minor label_minor    bgn
## 4 fit.models_0_Max.cor.Y.rcv.*X*          1          3      glmnet 34.014
## 5         fit.models_0_Low.cor.X          1          4      glmnet 42.582
##      end elapsed
## 4 42.581   8.567
## 5     NA      NA
indep_vars <- subset(glb_feats_df, is.na(cor.high.X) & !nzv & 
                              (exclude.as.feat != 1))[, "id"]  
indep_vars <- myadjust_interaction_feats(indep_vars)
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
            id.prefix = "Low.cor.X", 
            type = glb_model_type, 
            tune.df = glbMdlTuneParams,        
            trainControl.method = "repeatedcv",
            trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            trainControl.allowParallel = glbMdlAllowParallel,
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method = "glmnet")),
        indep_vars = indep_vars, rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Low.cor.X##rcv#glmnet"
## [1] "    indep_vars: .pos,PassengerId,.rnorm,Pclass.fctr"
## [1] "myfit_mdl: setup complete: 0.755000 secs"
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 0.325, lambda = 0.0182 on full training set
## [1] "myfit_mdl: train complete: 2.902000 secs"

##             Length Class      Mode     
## a0           62    -none-     numeric  
## beta        310    dgCMatrix  S4       
## df           62    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       62    -none-     numeric  
## dev.ratio    62    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## classnames    2    -none-     character
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames        5    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     2    -none-     character
## [1] "min lambda > lambdaOpt:"
##  (Intercept)       .rnorm Pclass.fctr2 Pclass.fctr3 
##   0.58568143  -0.04942397  -0.54820395  -1.80986086 
## [1] "max lambda < lambdaOpt:"
##  (Intercept)       .rnorm Pclass.fctr2 Pclass.fctr3 
##   0.60259812  -0.05186662  -0.57076451  -1.83424841 
## [1] "myfit_mdl: train diagnostics complete: 3.502000 secs"

##          Prediction
## Reference   N   Y
##         N 224  89
##         Y  60 137
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   7.078431e-01   4.001705e-01   6.662695e-01   7.469880e-01   6.137255e-01 
## AccuracyPValue  McnemarPValue 
##   5.482557e-06   2.179915e-02

##          Prediction
## Reference   N   Y
##         N   0 236
##         Y   0 145
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   3.805774e-01   0.000000e+00   3.316072e-01   4.314187e-01   6.194226e-01 
## AccuracyPValue  McnemarPValue 
##   1.000000e+00   7.982101e-53 
## [1] "myfit_mdl: predict complete: 5.579000 secs"
##                      id                               feats
## 1 Low.cor.X##rcv#glmnet .pos,PassengerId,.rnorm,Pclass.fctr
##   max.nTuningRuns min.elapsedtime.everything min.elapsedtime.final
## 1              20                      2.142                 0.012
##   max.AUCpROC.fit max.Sens.fit max.Spec.fit max.AUCROCR.fit
## 1       0.7121114    0.7795527    0.6446701       0.7254018
##   opt.prob.threshold.fit max.f.score.fit max.Accuracy.fit
## 1                    0.4       0.6477541        0.7105259
##   max.AccuracyLower.fit max.AccuracyUpper.fit max.Kappa.fit
## 1             0.6662695              0.746988     0.3808203
##   max.AUCpROC.OOB max.Sens.OOB max.Spec.OOB max.AUCROCR.OOB
## 1       0.6212011     0.690678    0.5517241       0.6326125
##   opt.prob.threshold.OOB max.f.score.OOB max.Accuracy.OOB
## 1                    0.1       0.5513308        0.3805774
##   max.AccuracyLower.OOB max.AccuracyUpper.OOB max.Kappa.OOB
## 1             0.3316072             0.4314187             0
##   max.AccuracySD.fit max.KappaSD.fit
## 1         0.04652983      0.09788933
## [1] "myfit_mdl: exit: 5.594000 secs"
fit.models_0_chunk_df <- 
    myadd_chunk(fit.models_0_chunk_df, "fit.models_0_end", major.inc = FALSE,
                label.minor = "teardown")
##                    label step_major step_minor label_minor    bgn    end
## 5 fit.models_0_Low.cor.X          1          4      glmnet 42.582 48.211
## 6       fit.models_0_end          1          5    teardown 48.212     NA
##   elapsed
## 5   5.629
## 6      NA
rm(ret_lst)

glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc = FALSE)
##         label step_major step_minor label_minor    bgn    end elapsed
## 16 fit.models          8          0           0 27.978 48.225  20.247
## 17 fit.models          8          1           1 48.226     NA      NA
fit.models_1_chunk_df <- myadd_chunk(NULL, "fit.models_1_bgn", label.minor = "setup")
##              label step_major step_minor label_minor    bgn end elapsed
## 1 fit.models_1_bgn          1          0       setup 51.346  NA      NA
# refactor code for outliers / ensure all model runs exclude outliers in this chunk ???

#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)
topindep_var <- NULL; interact_vars <- NULL;
for (mdl_id_pfx in names(glbMdlFamilies)) {
    fit.models_1_chunk_df <- 
        myadd_chunk(fit.models_1_chunk_df, paste0("fit.models_1_", mdl_id_pfx),
                    major.inc = FALSE, label.minor = "setup")

    indep_vars <- NULL;

    if (grepl("\\.Interact", mdl_id_pfx)) {
        if (is.null(topindep_var) && is.null(interact_vars)) {
        #   select best glmnet model upto now
            dsp_models_df <- orderBy(model_sel_frmla <- get_model_sel_frmla(),
                                     glb_models_df)
            dsp_models_df <- subset(dsp_models_df, 
                                    grepl(".glmnet", id, fixed = TRUE))
            bst_mdl_id <- dsp_models_df$id[1]
            mdl_id_pfx <- 
                paste(c(head(unlist(strsplit(bst_mdl_id, "[.]")), -1), "Interact"),
                      collapse=".")
        #   select important features
            if (is.null(bst_featsimp_df <- 
                        myget_feats_importance(glb_models_lst[[bst_mdl_id]]))) {
                warning("Base model for RFE.Interact: ", bst_mdl_id, 
                        " has no important features")
                next
            }    
            
            topindep_ix <- 1
            while (is.null(topindep_var) && (topindep_ix <= nrow(bst_featsimp_df))) {
                topindep_var <- row.names(bst_featsimp_df)[topindep_ix]
                if (grepl(".fctr", topindep_var, fixed=TRUE))
                    topindep_var <- 
                        paste0(unlist(strsplit(topindep_var, ".fctr"))[1], ".fctr")
                if (topindep_var %in% names(glbFeatsInteractionOnly)) {
                    topindep_var <- NULL; topindep_ix <- topindep_ix + 1
                } else break
            }
            
        #   select features with importance > max(10, importance of .rnorm) & is not highest
        #       combine factor dummy features to just the factor feature
            if (length(pos_rnorm <- 
                       grep(".rnorm", row.names(bst_featsimp_df), fixed=TRUE)) > 0)
                imp_rnorm <- bst_featsimp_df[pos_rnorm, 1] else
                imp_rnorm <- NA    
            imp_cutoff <- max(10, imp_rnorm, na.rm=TRUE)
            interact_vars <- 
                tail(row.names(subset(bst_featsimp_df, 
                                      imp > imp_cutoff)), -1)
            if (length(interact_vars) > 0) {
                interact_vars <-
                    myadjust_interaction_feats(myextract_actual_feats(interact_vars))
                interact_vars <- 
                    interact_vars[!grepl(topindep_var, interact_vars, fixed=TRUE)]
            }
            ### bid0_sp only
#             interact_vars <- c(
#     "biddable", "D.ratio.sum.TfIdf.wrds.n", "D.TfIdf.sum.stem.stop.Ratio", "D.sum.TfIdf",
#     "D.TfIdf.sum.post.stop", "D.TfIdf.sum.post.stem", "D.ratio.wrds.stop.n.wrds.n", "D.chrs.uppr.n.log",
#     "D.chrs.n.log", "color.fctr"
#     # , "condition.fctr", "prdl.my.descr.fctr"
#                                 )
#            interact_vars <- setdiff(interact_vars, c("startprice.dgt2.is9", "color.fctr"))
            ###
            indep_vars <- myextract_actual_feats(row.names(bst_featsimp_df))
            indep_vars <- setdiff(indep_vars, topindep_var)
            if (length(interact_vars) > 0) {
                indep_vars <- 
                    setdiff(indep_vars, myextract_actual_feats(interact_vars))
                indep_vars <- c(indep_vars, 
                    paste(topindep_var, setdiff(interact_vars, topindep_var), 
                          sep = "*"))
            } else indep_vars <- union(indep_vars, topindep_var)
        }
    }
    
    if (is.null(indep_vars))
        indep_vars <- glb_mdl_feats_lst[[mdl_id_pfx]]

    if (is.null(indep_vars) && grepl("RFE\\.", mdl_id_pfx))
        indep_vars <- myextract_actual_feats(predictors(rfe_fit_results))
    
    if (is.null(indep_vars))
        indep_vars <- subset(glb_feats_df, !nzv & (exclude.as.feat != 1))[, "id"]
    
    if ((length(indep_vars) == 1) && (grepl("^%<d-%", indep_vars))) {    
        indep_vars <- 
            eval(parse(text = str_trim(unlist(strsplit(indep_vars, "%<d-%"))[2])))
    }    

    indep_vars <- myadjust_interaction_feats(indep_vars)
    
    if (grepl("\\.Interact", mdl_id_pfx)) { 
        # if (method != tail(unlist(strsplit(bst_mdl_id, "[.]")), 1)) next
        if (is.null(glbMdlFamilies[[mdl_id_pfx]])) {
            if (!is.null(glbMdlFamilies[["Best.Interact"]]))
                glbMdlFamilies[[mdl_id_pfx]] <-
                    glbMdlFamilies[["Best.Interact"]]
        }
    }
    
    if (!is.null(glbObsFitOutliers[[mdl_id_pfx]])) {
        fitobs_df <- glbObsFit[!(glbObsFit[, glbFeatsId] %in%
                                         glbObsFitOutliers[[mdl_id_pfx]]), ]
        print(sprintf("Outliers removed: %d", nrow(glbObsFit) - nrow(fitobs_df)))
        print(setdiff(glbObsFit[, glbFeatsId], fitobs_df[, glbFeatsId]))
    } else fitobs_df <- glbObsFit

    if (is.null(glbMdlFamilies[[mdl_id_pfx]]))
        mdl_methods <- glbMdlMethods else
        mdl_methods <- glbMdlFamilies[[mdl_id_pfx]]    

    for (method in mdl_methods) {
        if (method %in% c("rpart", "rf")) {
            # rpart:    fubar's the tree
            # rf:       skip the scenario w/ .rnorm for speed
            indep_vars <- setdiff(indep_vars, c(".rnorm"))
            #mdl_id <- paste0(mdl_id_pfx, ".no.rnorm")
        } 

        fit.models_1_chunk_df <- myadd_chunk(fit.models_1_chunk_df, 
                            paste0("fit.models_1_", mdl_id_pfx), major.inc = FALSE,
                                    label.minor = method)

        ret_lst <- 
            myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
            id.prefix = mdl_id_pfx, 
            type = glb_model_type, 
            tune.df = glbMdlTuneParams,
            trainControl.method = "repeatedcv", # or "none" if nominalWorkflow is crashing
            trainControl.number = glb_rcv_n_folds,
            trainControl.repeats = glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            trainControl.allowParallel = glbMdlAllowParallel,            
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method = method)),
            indep_vars = indep_vars, rsp_var = glb_rsp_var, 
            fit_df = fitobs_df, OOB_df = glbObsOOB)
        
#         ntv_mdl <- glmnet(x = as.matrix(
#                               fitobs_df[, indep_vars]), 
#                           y = as.factor(as.character(
#                               fitobs_df[, glb_rsp_var])),
#                           family = "multinomial")
#         bgn = 1; end = 100;
#         ntv_mdl <- glmnet(x = as.matrix(
#                               subset(fitobs_df, pop.fctr != "crypto")[bgn:end, indep_vars]), 
#                           y = as.factor(as.character(
#                               subset(fitobs_df, pop.fctr != "crypto")[bgn:end, glb_rsp_var])),
#                           family = "multinomial")
    }
}
##                label step_major step_minor label_minor    bgn    end
## 1   fit.models_1_bgn          1          0       setup 51.346 51.356
## 2 fit.models_1_All.X          1          1       setup 51.357     NA
##   elapsed
## 1   0.011
## 2      NA
##                label step_major step_minor label_minor    bgn    end
## 2 fit.models_1_All.X          1          1       setup 51.357 51.363
## 3 fit.models_1_All.X          1          2      glmnet 51.364     NA
##   elapsed
## 2   0.006
## 3      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: All.X##rcv#glmnet"
## [1] "    indep_vars: .pos,PassengerId,.rnorm,Pclass.fctr"
## [1] "myfit_mdl: setup complete: 1.035000 secs"
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 0.325, lambda = 0.0182 on full training set
## [1] "myfit_mdl: train complete: 2.872000 secs"

##             Length Class      Mode     
## a0           62    -none-     numeric  
## beta        310    dgCMatrix  S4       
## df           62    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       62    -none-     numeric  
## dev.ratio    62    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## classnames    2    -none-     character
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames        5    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     2    -none-     character
## [1] "min lambda > lambdaOpt:"
##  (Intercept)       .rnorm Pclass.fctr2 Pclass.fctr3 
##   0.58568143  -0.04942397  -0.54820395  -1.80986086 
## [1] "max lambda < lambdaOpt:"
##  (Intercept)       .rnorm Pclass.fctr2 Pclass.fctr3 
##   0.60259812  -0.05186662  -0.57076451  -1.83424841 
## [1] "myfit_mdl: train diagnostics complete: 3.544000 secs"

##          Prediction
## Reference   N   Y
##         N 224  89
##         Y  60 137
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   7.078431e-01   4.001705e-01   6.662695e-01   7.469880e-01   6.137255e-01 
## AccuracyPValue  McnemarPValue 
##   5.482557e-06   2.179915e-02

##          Prediction
## Reference   N   Y
##         N   0 236
##         Y   0 145
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   3.805774e-01   0.000000e+00   3.316072e-01   4.314187e-01   6.194226e-01 
## AccuracyPValue  McnemarPValue 
##   1.000000e+00   7.982101e-53 
## [1] "myfit_mdl: predict complete: 6.028000 secs"
##                  id                               feats max.nTuningRuns
## 1 All.X##rcv#glmnet .pos,PassengerId,.rnorm,Pclass.fctr              20
##   min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1                      1.832                 0.012       0.7121114
##   max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1    0.7795527    0.6446701       0.7254018                    0.4
##   max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1       0.6477541        0.7105259             0.6662695
##   max.AccuracyUpper.fit max.Kappa.fit max.AUCpROC.OOB max.Sens.OOB
## 1              0.746988     0.3808203       0.6212011     0.690678
##   max.Spec.OOB max.AUCROCR.OOB opt.prob.threshold.OOB max.f.score.OOB
## 1    0.5517241       0.6326125                    0.1       0.5513308
##   max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1        0.3805774             0.3316072             0.4314187
##   max.Kappa.OOB max.AccuracySD.fit max.KappaSD.fit
## 1             0         0.04652983      0.09788933
## [1] "myfit_mdl: exit: 6.043000 secs"
##                label step_major step_minor label_minor    bgn    end
## 3 fit.models_1_All.X          1          2      glmnet 51.364 57.412
## 4 fit.models_1_All.X          1          3         glm 57.412     NA
##   elapsed
## 3   6.048
## 4      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: All.X##rcv#glm"
## [1] "    indep_vars: .pos,PassengerId,.rnorm,Pclass.fctr"
## [1] "myfit_mdl: setup complete: 0.735000 secs"
## Aggregating results
## Fitting final model on full training set
## [1] "myfit_mdl: train complete: 1.943000 secs"

## 
## Call:
## NULL
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.6069  -0.7111  -0.6767   0.8782   1.8679  
## 
## Coefficients: (1 not defined because of singularities)
##                Estimate Std. Error z value Pr(>|z|)    
## (Intercept)   7.700e-01  2.625e-01   2.933  0.00336 ** 
## .pos          7.512e-05  3.877e-04   0.194  0.84636    
## .rnorm       -7.964e-02  9.840e-02  -0.809  0.41833    
## PassengerId          NA         NA      NA       NA    
## Pclass.fctr2 -8.405e-01  2.795e-01  -3.007  0.00263 ** 
## Pclass.fctr3 -2.122e+00  2.397e-01  -8.850  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 680.39  on 509  degrees of freedom
## Residual deviance: 585.71  on 505  degrees of freedom
## AIC: 595.71
## 
## Number of Fisher Scoring iterations: 4
## 
## [1] "myfit_mdl: train diagnostics complete: 2.690000 secs"
## Warning in predict.lm(object, newdata, se.fit, scale = 1, type =
## ifelse(type == : prediction from a rank-deficient fit may be misleading

## Warning in predict.lm(object, newdata, se.fit, scale = 1, type =
## ifelse(type == : prediction from a rank-deficient fit may be misleading

##          Prediction
## Reference   N   Y
##         N 224  89
##         Y  60 137
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   7.078431e-01   4.001705e-01   6.662695e-01   7.469880e-01   6.137255e-01 
## AccuracyPValue  McnemarPValue 
##   5.482557e-06   2.179915e-02
## Warning in predict.lm(object, newdata, se.fit, scale = 1, type =
## ifelse(type == : prediction from a rank-deficient fit may be misleading

## Warning in predict.lm(object, newdata, se.fit, scale = 1, type =
## ifelse(type == : prediction from a rank-deficient fit may be misleading

##          Prediction
## Reference   N   Y
##         N   0 236
##         Y   0 145
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   3.805774e-01   0.000000e+00   3.316072e-01   4.314187e-01   6.194226e-01 
## AccuracyPValue  McnemarPValue 
##   1.000000e+00   7.982101e-53 
## [1] "myfit_mdl: predict complete: 5.141000 secs"
##               id                               feats max.nTuningRuns
## 1 All.X##rcv#glm .pos,PassengerId,.rnorm,Pclass.fctr               1
##   min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1                      1.202                 0.012        0.692642
##   max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1    0.8370607    0.5482234       0.7263749                    0.4
##   max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1       0.6477541        0.7046551             0.6662695
##   max.AccuracyUpper.fit max.Kappa.fit max.AUCpROC.OOB max.Sens.OOB
## 1              0.746988     0.3602641       0.6091905    0.7838983
##   max.Spec.OOB max.AUCROCR.OOB opt.prob.threshold.OOB max.f.score.OOB
## 1    0.4344828       0.6265634                    0.1       0.5513308
##   max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1        0.3805774             0.3316072             0.4314187
##   max.Kappa.OOB max.AccuracySD.fit max.KappaSD.fit
## 1             0         0.04258373      0.08610365
## [1] "myfit_mdl: exit: 5.156000 secs"
# Check if other preProcess methods improve model performance
fit.models_1_chunk_df <- 
    myadd_chunk(fit.models_1_chunk_df, "fit.models_1_preProc", major.inc = FALSE,
                label.minor = "preProc")
##                  label step_major step_minor label_minor    bgn    end
## 4   fit.models_1_All.X          1          3         glm 57.412 62.592
## 5 fit.models_1_preProc          1          4     preProc 62.593     NA
##   elapsed
## 4    5.18
## 5      NA
mdl_id <- orderBy(get_model_sel_frmla(), glb_models_df)[1, "id"]
indep_vars_vctr <- trim(unlist(strsplit(glb_models_df[glb_models_df$id == mdl_id,
                                                      "feats"], "[,]")))
method <- tail(unlist(strsplit(mdl_id, "[.]")), 1)
mdl_id_pfx <- paste0(head(unlist(strsplit(mdl_id, "[.]")), -1), collapse = ".")
if (!is.null(glbObsFitOutliers[[mdl_id_pfx]])) {
    fitobs_df <- glbObsFit[!(glbObsFit[, glbFeatsId] %in%
                                     glbObsFitOutliers[[mdl_id_pfx]]), ]
        print(sprintf("Outliers removed: %d", nrow(glbObsFit) - nrow(fitobs_df)))
        print(setdiff(glbObsFit[, glbFeatsId], fitobs_df[, glbFeatsId]))
    
} else fitobs_df <- glbObsFit

for (prePr in glb_preproc_methods) {   
    # The operations are applied in this order: 
    #   Box-Cox/Yeo-Johnson transformation, centering, scaling, range, imputation, PCA, ICA then spatial sign.
    
    ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
            id.prefix=mdl_id_pfx, 
            type=glb_model_type, tune.df=glbMdlTuneParams,
            trainControl.method="repeatedcv",
            trainControl.number=glb_rcv_n_folds,
            trainControl.repeats=glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method=method, train.preProcess=prePr)),
            indep_vars=indep_vars_vctr, rsp_var=glb_rsp_var, 
            fit_df=fitobs_df, OOB_df=glbObsOOB)
}            
    
    # If (All|RFE).X.glm is less accurate than Low.Cor.X.glm
    #   check NA coefficients & filter appropriate terms in indep_vars_vctr
#     if (method == "glm") {
#         orig_glm <- glb_models_lst[[paste0(mdl_id, ".", model_method)]]$finalModel
#         orig_glm <- glb_models_lst[["All.X.glm"]]$finalModel; print(summary(orig_glm))
#         orig_glm <- glb_models_lst[["RFE.X.glm"]]$finalModel; print(summary(orig_glm))
#           require(car)
#           vif_orig_glm <- vif(orig_glm); print(vif_orig_glm)
#           # if vif errors out with "there are aliased coefficients in the model"
#               alias_orig_glm <- alias(orig_glm); alias_complete_orig_glm <- (alias_orig_glm$Complete > 0); alias_complete_orig_glm <- alias_complete_orig_glm[rowSums(alias_complete_orig_glm) > 0, colSums(alias_complete_orig_glm) > 0]; print(alias_complete_orig_glm)
#           print(vif_orig_glm[!is.na(vif_orig_glm) & (vif_orig_glm == Inf)])
#           print(which.max(vif_orig_glm))
#           print(sort(vif_orig_glm[vif_orig_glm >= 1.0e+03], decreasing=TRUE))
#           glbObsFit[c(1143, 3637, 3953, 4105), c("UniqueID", "Popular", "H.P.quandary", "Headline")]
#           glb_feats_df[glb_feats_df$id %in% grep("[HSA]\\.chrs.n.log", glb_feats_df$id, value=TRUE) | glb_feats_df$cor.high.X %in%    grep("[HSA]\\.chrs.n.log", glb_feats_df$id, value=TRUE), ]
#           all.equal(glbObsAll$S.chrs.uppr.n.log, glbObsAll$A.chrs.uppr.n.log)
#           cor(glbObsAll$S.T.herald, glbObsAll$S.T.tribun)
#           mydspObs(Abstract.contains="[Dd]iar", cols=("Abstract"), all=TRUE)
#           subset(glb_feats_df, cor.y.abs <= glb_feats_df[glb_feats_df$id == ".rnorm", "cor.y.abs"])
#         corxx_mtrx <- cor(data.matrix(glbObsAll[, setdiff(names(glbObsAll), myfind_chr_cols_df(glbObsAll))]), use="pairwise.complete.obs"); abs_corxx_mtrx <- abs(corxx_mtrx); diag(abs_corxx_mtrx) <- 0
#           which.max(abs_corxx_mtrx["S.T.tribun", ])
#           abs_corxx_mtrx["A.npnct08.log", "S.npnct08.log"]
#         step_glm <- step(orig_glm)
#     }
    # Since caret does not optimize rpart well
#     if (method == "rpart")
#         ret_lst <- myfit_mdl(mdl_id=paste0(mdl_id_pfx, ".cp.0"), model_method=method,
#                                 indep_vars_vctr=indep_vars_vctr,
#                                 model_type=glb_model_type,
#                                 rsp_var=glb_rsp_var,
#                                 fit_df=glbObsFit, OOB_df=glbObsOOB,        
#             n_cv_folds=0, tune_models_df=data.frame(parameter="cp", min=0.0, max=0.0, by=0.1))

# User specified
#   Ensure at least 2 vars in each regression; else varImp crashes
# sav_models_lst <- glb_models_lst; sav_models_df <- glb_models_df; sav_featsimp_df <- glb_featsimp_df; all.equal(sav_featsimp_df, glb_featsimp_df)
# glb_models_lst <- sav_models_lst; glb_models_df <- sav_models_df; glm_featsimp_df <- sav_featsimp_df

    # easier to exclude features
# require(gdata) # needed for trim
# mdl_id <- "";
# indep_vars_vctr <- head(subset(glb_models_df, grepl("All\\.X\\.", mdl_id), select=feats)
#                         , 1)[, "feats"]
# indep_vars_vctr <- trim(unlist(strsplit(indep_vars_vctr, "[,]")))
# indep_vars_vctr <- setdiff(indep_vars_vctr, ".rnorm")

    # easier to include features
#stop(here"); sav_models_df <- glb_models_df; glb_models_df <- sav_models_df
# !_sp
# mdl_id <- "csm"; indep_vars_vctr <- c(NULL
#     ,"prdline.my.fctr", "prdline.my.fctr:.clusterid.fctr"
#     ,"prdline.my.fctr*biddable"
#     #,"prdline.my.fctr*startprice.log"
#     #,"prdline.my.fctr*startprice.diff"    
#     ,"prdline.my.fctr*condition.fctr"
#     ,"prdline.my.fctr*D.terms.post.stop.n"
#     #,"prdline.my.fctr*D.terms.post.stem.n"
#     ,"prdline.my.fctr*cellular.fctr"    
# #    ,"<feat1>:<feat2>"
#                                            )
# for (method in glbMdlMethods) {
#     ret_lst <- myfit_mdl(mdl_id=mdl_id, model_method=method,
#                                 indep_vars_vctr=indep_vars_vctr,
#                                 model_type=glb_model_type,
#                                 rsp_var=glb_rsp_var,
#                                 fit_df=glbObsFit, OOB_df=glbObsOOB,
#                     n_cv_folds=glb_rcv_n_folds, tune_models_df=glbMdlTuneParams)
#     csm_mdl_id <- paste0(mdl_id, ".", method)
#     csm_featsimp_df <- myget_feats_importance(glb_models_lst[[paste0(mdl_id, ".",
#                                                                      method)]]);               print(head(csm_featsimp_df))
# }
###

# Ntv.1.lm <- lm(reformulate(indep_vars_vctr, glb_rsp_var), glbObsTrn); print(summary(Ntv.1.lm))

#glb_models_df[, "max.Accuracy.OOB", FALSE]
#varImp(glb_models_lst[["Low.cor.X.glm"]])
#orderBy(~ -Overall, varImp(glb_models_lst[["All.X.2.glm"]])$imp)
#orderBy(~ -Overall, varImp(glb_models_lst[["All.X.3.glm"]])$imp)
#glb_feats_df[grepl("npnct28", glb_feats_df$id), ]

    # User specified bivariate models
#     indep_vars_vctr_lst <- list()
#     for (feat in setdiff(names(glbObsFit), 
#                          union(glb_rsp_var, glbFeatsExclude)))
#         indep_vars_vctr_lst[["feat"]] <- feat

    # User specified combinatorial models
#     indep_vars_vctr_lst <- list()
#     combn_mtrx <- combn(c("<feat1_name>", "<feat2_name>", "<featn_name>"), 
#                           <num_feats_to_choose>)
#     for (combn_ix in 1:ncol(combn_mtrx))
#         #print(combn_mtrx[, combn_ix])
#         indep_vars_vctr_lst[[combn_ix]] <- combn_mtrx[, combn_ix]
    
    # template for myfit_mdl
    #   rf is hard-coded in caret to recognize only Accuracy / Kappa evaluation metrics
    #       only for OOB in trainControl ?
    
#     ret_lst <- myfit_mdl_fn(mdl_id=paste0(mdl_id_pfx, ""), model_method=method,
#                             indep_vars_vctr=indep_vars_vctr,
#                             rsp_var=glb_rsp_var,
#                             fit_df=glbObsFit, OOB_df=glbObsOOB,
#                             n_cv_folds=glb_rcv_n_folds, tune_models_df=glbMdlTuneParams,
#                             model_loss_mtrx=glbMdlMetric_terms,
#                             model_summaryFunction=glbMdlMetricSummaryFn,
#                             model_metric=glbMdlMetricSummary,
#                             model_metric_maximize=glbMdlMetricMaximize)

# Simplify a model
# fit_df <- glbObsFit; glb_mdl <- step(<complex>_mdl)

# Non-caret models
#     rpart_area_mdl <- rpart(reformulate("Area", response=glb_rsp_var), 
#                                data=glbObsFit, #method="class", 
#                                control=rpart.control(cp=0.12),
#                            parms=list(loss=glbMdlMetric_terms))
#     print("rpart_sel_wlm_mdl"); prp(rpart_sel_wlm_mdl)
# 

print(glb_models_df)
##                                                    id
## MFO###myMFO_classfr               MFO###myMFO_classfr
## Random###myrandom_classfr   Random###myrandom_classfr
## Max.cor.Y.rcv.1X1###glmnet Max.cor.Y.rcv.1X1###glmnet
## Max.cor.Y##rcv#rpart             Max.cor.Y##rcv#rpart
## Low.cor.X##rcv#glmnet           Low.cor.X##rcv#glmnet
## All.X##rcv#glmnet                   All.X##rcv#glmnet
## All.X##rcv#glm                         All.X##rcv#glm
##                                                          feats
## MFO###myMFO_classfr                                     .rnorm
## Random###myrandom_classfr                               .rnorm
## Max.cor.Y.rcv.1X1###glmnet                  Pclass.fctr,.rnorm
## Max.cor.Y##rcv#rpart                        Pclass.fctr,.rnorm
## Low.cor.X##rcv#glmnet      .pos,PassengerId,.rnorm,Pclass.fctr
## All.X##rcv#glmnet          .pos,PassengerId,.rnorm,Pclass.fctr
## All.X##rcv#glm             .pos,PassengerId,.rnorm,Pclass.fctr
##                            max.nTuningRuns min.elapsedtime.everything
## MFO###myMFO_classfr                      0                      0.365
## Random###myrandom_classfr                0                      0.268
## Max.cor.Y.rcv.1X1###glmnet               0                      0.710
## Max.cor.Y##rcv#rpart                     5                      1.628
## Low.cor.X##rcv#glmnet                   20                      2.142
## All.X##rcv#glmnet                       20                      1.832
## All.X##rcv#glm                           1                      1.202
##                            min.elapsedtime.final max.AUCpROC.fit
## MFO###myMFO_classfr                        0.004       0.5000000
## Random###myrandom_classfr                  0.002       0.5093819
## Max.cor.Y.rcv.1X1###glmnet                 0.016       0.6970614
## Max.cor.Y##rcv#rpart                       0.013       0.7115438
## Low.cor.X##rcv#glmnet                      0.012       0.7121114
## All.X##rcv#glmnet                          0.012       0.7121114
## All.X##rcv#glm                             0.012       0.6926420
##                            max.Sens.fit max.Spec.fit max.AUCROCR.fit
## MFO###myMFO_classfr           1.0000000    0.0000000       0.5000000
## Random###myrandom_classfr     0.5974441    0.4213198       0.5620084
## Max.cor.Y.rcv.1X1###glmnet    0.8306709    0.5634518       0.7254018
## Max.cor.Y##rcv#rpart          0.7987220    0.6243655       0.7304050
## Low.cor.X##rcv#glmnet         0.7795527    0.6446701       0.7254018
## All.X##rcv#glmnet             0.7795527    0.6446701       0.7254018
## All.X##rcv#glm                0.8370607    0.5482234       0.7263749
##                            opt.prob.threshold.fit max.f.score.fit
## MFO###myMFO_classfr                           0.3       0.5572843
## Random###myrandom_classfr                     0.3       0.5572843
## Max.cor.Y.rcv.1X1###glmnet                    0.4       0.6477541
## Max.cor.Y##rcv#rpart                          0.3       0.6477541
## Low.cor.X##rcv#glmnet                         0.4       0.6477541
## All.X##rcv#glmnet                             0.4       0.6477541
## All.X##rcv#glm                                0.4       0.6477541
##                            max.Accuracy.fit max.AccuracyLower.fit
## MFO###myMFO_classfr               0.3862745             0.3438031
## Random###myrandom_classfr         0.3862745             0.3438031
## Max.cor.Y.rcv.1X1###glmnet        0.7078431             0.6662695
## Max.cor.Y##rcv#rpart              0.7078962             0.6662695
## Low.cor.X##rcv#glmnet             0.7105259             0.6662695
## All.X##rcv#glmnet                 0.7105259             0.6662695
## All.X##rcv#glm                    0.7046551             0.6662695
##                            max.AccuracyUpper.fit max.Kappa.fit
## MFO###myMFO_classfr                    0.4300722     0.0000000
## Random###myrandom_classfr              0.4300722     0.0000000
## Max.cor.Y.rcv.1X1###glmnet             0.7469880     0.4001705
## Max.cor.Y##rcv#rpart                   0.7469880     0.3659851
## Low.cor.X##rcv#glmnet                  0.7469880     0.3808203
## All.X##rcv#glmnet                      0.7469880     0.3808203
## All.X##rcv#glm                         0.7469880     0.3602641
##                            max.AUCpROC.OOB max.Sens.OOB max.Spec.OOB
## MFO###myMFO_classfr              0.5000000    1.0000000    0.0000000
## Random###myrandom_classfr        0.4867621    0.6355932    0.3379310
## Max.cor.Y.rcv.1X1###glmnet       0.6118498    0.7754237    0.4482759
## Max.cor.Y##rcv#rpart             0.6137639    0.7033898    0.5241379
## Low.cor.X##rcv#glmnet            0.6212011    0.6906780    0.5517241
## All.X##rcv#glmnet                0.6212011    0.6906780    0.5517241
## All.X##rcv#glm                   0.6091905    0.7838983    0.4344828
##                            max.AUCROCR.OOB opt.prob.threshold.OOB
## MFO###myMFO_classfr              0.5000000                    0.3
## Random###myrandom_classfr        0.4456750                    0.3
## Max.cor.Y.rcv.1X1###glmnet       0.6326125                    0.2
## Max.cor.Y##rcv#rpart             0.6225015                    0.2
## Low.cor.X##rcv#glmnet            0.6326125                    0.1
## All.X##rcv#glmnet                0.6326125                    0.1
## All.X##rcv#glm                   0.6265634                    0.1
##                            max.f.score.OOB max.Accuracy.OOB
## MFO###myMFO_classfr              0.5513308        0.3805774
## Random###myrandom_classfr        0.5513308        0.3805774
## Max.cor.Y.rcv.1X1###glmnet       0.5520000        0.4120735
## Max.cor.Y##rcv#rpart             0.5513308        0.3805774
## Low.cor.X##rcv#glmnet            0.5513308        0.3805774
## All.X##rcv#glmnet                0.5513308        0.3805774
## All.X##rcv#glm                   0.5513308        0.3805774
##                            max.AccuracyLower.OOB max.AccuracyUpper.OOB
## MFO###myMFO_classfr                    0.3316072             0.4314187
## Random###myrandom_classfr              0.3316072             0.4314187
## Max.cor.Y.rcv.1X1###glmnet             0.3621900             0.4633340
## Max.cor.Y##rcv#rpart                   0.3316072             0.4314187
## Low.cor.X##rcv#glmnet                  0.3316072             0.4314187
## All.X##rcv#glmnet                      0.3316072             0.4314187
## All.X##rcv#glm                         0.3316072             0.4314187
##                            max.Kappa.OOB max.AccuracySD.fit
## MFO###myMFO_classfr           0.00000000                 NA
## Random###myrandom_classfr     0.00000000                 NA
## Max.cor.Y.rcv.1X1###glmnet    0.02519703                 NA
## Max.cor.Y##rcv#rpart          0.00000000         0.03483382
## Low.cor.X##rcv#glmnet         0.00000000         0.04652983
## All.X##rcv#glmnet             0.00000000         0.04652983
## All.X##rcv#glm                0.00000000         0.04258373
##                            max.KappaSD.fit
## MFO###myMFO_classfr                     NA
## Random###myrandom_classfr               NA
## Max.cor.Y.rcv.1X1###glmnet              NA
## Max.cor.Y##rcv#rpart            0.07002241
## Low.cor.X##rcv#glmnet           0.09788933
## All.X##rcv#glmnet               0.09788933
## All.X##rcv#glm                  0.08610365
rm(ret_lst)
fit.models_1_chunk_df <- 
    myadd_chunk(fit.models_1_chunk_df, "fit.models_1_end", major.inc = FALSE,
                label.minor = "teardown")
##                  label step_major step_minor label_minor    bgn    end
## 5 fit.models_1_preProc          1          4     preProc 62.593 62.665
## 6     fit.models_1_end          1          5    teardown 62.666     NA
##   elapsed
## 5   0.072
## 6      NA
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc = FALSE)
##         label step_major step_minor label_minor    bgn    end elapsed
## 17 fit.models          8          1           1 48.226 62.675  14.449
## 18 fit.models          8          2           2 62.676     NA      NA
fit.models_2_chunk_df <- 
    myadd_chunk(NULL, "fit.models_2_bgn", label.minor = "setup")
##              label step_major step_minor label_minor    bgn end elapsed
## 1 fit.models_2_bgn          1          0       setup 65.879  NA      NA
plt_models_df <- glb_models_df[, -grep("SD|Upper|Lower", names(glb_models_df))]
for (var in grep("^min.", names(plt_models_df), value=TRUE)) {
    plt_models_df[, sub("min.", "inv.", var)] <- 
        #ifelse(all(is.na(tmp <- plt_models_df[, var])), NA, 1.0 / tmp)
        1.0 / plt_models_df[, var]
    plt_models_df <- plt_models_df[ , -grep(var, names(plt_models_df))]
}
print(plt_models_df)
##                                                    id
## MFO###myMFO_classfr               MFO###myMFO_classfr
## Random###myrandom_classfr   Random###myrandom_classfr
## Max.cor.Y.rcv.1X1###glmnet Max.cor.Y.rcv.1X1###glmnet
## Max.cor.Y##rcv#rpart             Max.cor.Y##rcv#rpart
## Low.cor.X##rcv#glmnet           Low.cor.X##rcv#glmnet
## All.X##rcv#glmnet                   All.X##rcv#glmnet
## All.X##rcv#glm                         All.X##rcv#glm
##                                                          feats
## MFO###myMFO_classfr                                     .rnorm
## Random###myrandom_classfr                               .rnorm
## Max.cor.Y.rcv.1X1###glmnet                  Pclass.fctr,.rnorm
## Max.cor.Y##rcv#rpart                        Pclass.fctr,.rnorm
## Low.cor.X##rcv#glmnet      .pos,PassengerId,.rnorm,Pclass.fctr
## All.X##rcv#glmnet          .pos,PassengerId,.rnorm,Pclass.fctr
## All.X##rcv#glm             .pos,PassengerId,.rnorm,Pclass.fctr
##                            max.nTuningRuns max.AUCpROC.fit max.Sens.fit
## MFO###myMFO_classfr                      0       0.5000000    1.0000000
## Random###myrandom_classfr                0       0.5093819    0.5974441
## Max.cor.Y.rcv.1X1###glmnet               0       0.6970614    0.8306709
## Max.cor.Y##rcv#rpart                     5       0.7115438    0.7987220
## Low.cor.X##rcv#glmnet                   20       0.7121114    0.7795527
## All.X##rcv#glmnet                       20       0.7121114    0.7795527
## All.X##rcv#glm                           1       0.6926420    0.8370607
##                            max.Spec.fit max.AUCROCR.fit
## MFO###myMFO_classfr           0.0000000       0.5000000
## Random###myrandom_classfr     0.4213198       0.5620084
## Max.cor.Y.rcv.1X1###glmnet    0.5634518       0.7254018
## Max.cor.Y##rcv#rpart          0.6243655       0.7304050
## Low.cor.X##rcv#glmnet         0.6446701       0.7254018
## All.X##rcv#glmnet             0.6446701       0.7254018
## All.X##rcv#glm                0.5482234       0.7263749
##                            opt.prob.threshold.fit max.f.score.fit
## MFO###myMFO_classfr                           0.3       0.5572843
## Random###myrandom_classfr                     0.3       0.5572843
## Max.cor.Y.rcv.1X1###glmnet                    0.4       0.6477541
## Max.cor.Y##rcv#rpart                          0.3       0.6477541
## Low.cor.X##rcv#glmnet                         0.4       0.6477541
## All.X##rcv#glmnet                             0.4       0.6477541
## All.X##rcv#glm                                0.4       0.6477541
##                            max.Accuracy.fit max.Kappa.fit max.AUCpROC.OOB
## MFO###myMFO_classfr               0.3862745     0.0000000       0.5000000
## Random###myrandom_classfr         0.3862745     0.0000000       0.4867621
## Max.cor.Y.rcv.1X1###glmnet        0.7078431     0.4001705       0.6118498
## Max.cor.Y##rcv#rpart              0.7078962     0.3659851       0.6137639
## Low.cor.X##rcv#glmnet             0.7105259     0.3808203       0.6212011
## All.X##rcv#glmnet                 0.7105259     0.3808203       0.6212011
## All.X##rcv#glm                    0.7046551     0.3602641       0.6091905
##                            max.Sens.OOB max.Spec.OOB max.AUCROCR.OOB
## MFO###myMFO_classfr           1.0000000    0.0000000       0.5000000
## Random###myrandom_classfr     0.6355932    0.3379310       0.4456750
## Max.cor.Y.rcv.1X1###glmnet    0.7754237    0.4482759       0.6326125
## Max.cor.Y##rcv#rpart          0.7033898    0.5241379       0.6225015
## Low.cor.X##rcv#glmnet         0.6906780    0.5517241       0.6326125
## All.X##rcv#glmnet             0.6906780    0.5517241       0.6326125
## All.X##rcv#glm                0.7838983    0.4344828       0.6265634
##                            opt.prob.threshold.OOB max.f.score.OOB
## MFO###myMFO_classfr                           0.3       0.5513308
## Random###myrandom_classfr                     0.3       0.5513308
## Max.cor.Y.rcv.1X1###glmnet                    0.2       0.5520000
## Max.cor.Y##rcv#rpart                          0.2       0.5513308
## Low.cor.X##rcv#glmnet                         0.1       0.5513308
## All.X##rcv#glmnet                             0.1       0.5513308
## All.X##rcv#glm                                0.1       0.5513308
##                            max.Accuracy.OOB max.Kappa.OOB
## MFO###myMFO_classfr               0.3805774    0.00000000
## Random###myrandom_classfr         0.3805774    0.00000000
## Max.cor.Y.rcv.1X1###glmnet        0.4120735    0.02519703
## Max.cor.Y##rcv#rpart              0.3805774    0.00000000
## Low.cor.X##rcv#glmnet             0.3805774    0.00000000
## All.X##rcv#glmnet                 0.3805774    0.00000000
## All.X##rcv#glm                    0.3805774    0.00000000
##                            inv.elapsedtime.everything
## MFO###myMFO_classfr                         2.7397260
## Random###myrandom_classfr                   3.7313433
## Max.cor.Y.rcv.1X1###glmnet                  1.4084507
## Max.cor.Y##rcv#rpart                        0.6142506
## Low.cor.X##rcv#glmnet                       0.4668534
## All.X##rcv#glmnet                           0.5458515
## All.X##rcv#glm                              0.8319468
##                            inv.elapsedtime.final
## MFO###myMFO_classfr                    250.00000
## Random###myrandom_classfr              500.00000
## Max.cor.Y.rcv.1X1###glmnet              62.50000
## Max.cor.Y##rcv#rpart                    76.92308
## Low.cor.X##rcv#glmnet                   83.33333
## All.X##rcv#glmnet                       83.33333
## All.X##rcv#glm                          83.33333
# print(myplot_radar(radar_inp_df=plt_models_df))
# print(myplot_radar(radar_inp_df=subset(plt_models_df, 
#         !(mdl_id %in% grep("random|MFO", plt_models_df$id, value=TRUE)))))

# Compute CI for <metric>SD
glb_models_df <- mutate(glb_models_df, 
                max.df = ifelse(max.nTuningRuns > 1, max.nTuningRuns - 1, NA),
                min.sd2ci.scaler = ifelse(is.na(max.df), NA, qt(0.975, max.df)))
for (var in grep("SD", names(glb_models_df), value=TRUE)) {
    # Does CI alredy exist ?
    var_components <- unlist(strsplit(var, "SD"))
    varActul <- paste0(var_components[1],          var_components[2])
    varUpper <- paste0(var_components[1], "Upper", var_components[2])
    varLower <- paste0(var_components[1], "Lower", var_components[2])
    if (varUpper %in% names(glb_models_df)) {
        warning(varUpper, " already exists in glb_models_df")
        # Assuming Lower also exists
        next
    }    
    print(sprintf("var:%s", var))
    # CI is dependent on sample size in t distribution; df=n-1
    glb_models_df[, varUpper] <- glb_models_df[, varActul] + 
        glb_models_df[, "min.sd2ci.scaler"] * glb_models_df[, var]
    glb_models_df[, varLower] <- glb_models_df[, varActul] - 
        glb_models_df[, "min.sd2ci.scaler"] * glb_models_df[, var]
}
## Warning: max.AccuracyUpper.fit already exists in glb_models_df
## [1] "var:max.KappaSD.fit"
# Plot metrics with CI
plt_models_df <- glb_models_df[, "id", FALSE]
pltCI_models_df <- glb_models_df[, "id", FALSE]
for (var in grep("Upper", names(glb_models_df), value=TRUE)) {
    var_components <- unlist(strsplit(var, "Upper"))
    col_name <- unlist(paste(var_components, collapse=""))
    plt_models_df[, col_name] <- glb_models_df[, col_name]
    for (name in paste0(var_components[1], c("Upper", "Lower"), var_components[2]))
        pltCI_models_df[, name] <- glb_models_df[, name]
}

build_statsCI_data <- function(plt_models_df) {
    mltd_models_df <- melt(plt_models_df, id.vars="id")
    mltd_models_df$data <- sapply(1:nrow(mltd_models_df), 
        function(row_ix) tail(unlist(strsplit(as.character(
            mltd_models_df[row_ix, "variable"]), "[.]")), 1))
    mltd_models_df$label <- sapply(1:nrow(mltd_models_df), 
        function(row_ix) head(unlist(strsplit(as.character(
            mltd_models_df[row_ix, "variable"]), 
            paste0(".", mltd_models_df[row_ix, "data"]))), 1))
    #print(mltd_models_df)
    
    return(mltd_models_df)
}
mltd_models_df <- build_statsCI_data(plt_models_df)

mltdCI_models_df <- melt(pltCI_models_df, id.vars="id")
for (row_ix in 1:nrow(mltdCI_models_df)) {
    for (type in c("Upper", "Lower")) {
        if (length(var_components <- unlist(strsplit(
                as.character(mltdCI_models_df[row_ix, "variable"]), type))) > 1) {
            #print(sprintf("row_ix:%d; type:%s; ", row_ix, type))
            mltdCI_models_df[row_ix, "label"] <- var_components[1]
            mltdCI_models_df[row_ix, "data"] <- 
                unlist(strsplit(var_components[2], "[.]"))[2]
            mltdCI_models_df[row_ix, "type"] <- type
            break
        }
    }    
}
wideCI_models_df <- reshape(subset(mltdCI_models_df, select=-variable), 
                            timevar="type", 
        idvar=setdiff(names(mltdCI_models_df), c("type", "value", "variable")), 
                            direction="wide")
#print(wideCI_models_df)
mrgdCI_models_df <- merge(wideCI_models_df, mltd_models_df, all.x=TRUE)
#print(mrgdCI_models_df)

# Merge stats back in if CIs don't exist
goback_vars <- c()
for (var in unique(mltd_models_df$label)) {
    for (type in unique(mltd_models_df$data)) {
        var_type <- paste0(var, ".", type)
        # if this data is already present, next
        if (var_type %in% unique(paste(mltd_models_df$label, mltd_models_df$data,
                                       sep=".")))
            next
        #print(sprintf("var_type:%s", var_type))
        goback_vars <- c(goback_vars, var_type)
    }
}

if (length(goback_vars) > 0) {
    mltd_goback_df <- build_statsCI_data(glb_models_df[, c("id", goback_vars)])
    mltd_models_df <- rbind(mltd_models_df, mltd_goback_df)
}

# mltd_models_df <- merge(mltd_models_df, glb_models_df[, c("id", "model_method")], 
#                         all.x=TRUE)

png(paste0(glbOut$pfx, "models_bar.png"), width=480*3, height=480*2)
#print(gp <- myplot_bar(mltd_models_df, "id", "value", colorcol_name="model_method") + 
print(gp <- myplot_bar(df=mltd_models_df, xcol_name="id", ycol_names="value") + 
        geom_errorbar(data=mrgdCI_models_df, 
            mapping=aes(x=mdl_id, ymax=value.Upper, ymin=value.Lower), width=0.5) + 
          facet_grid(label ~ data, scales="free") + 
          theme(axis.text.x = element_text(angle = 90,vjust = 0.5)))
## Warning: Removed 4 rows containing missing values (geom_errorbar).
dev.off()
## quartz_off_screen 
##                 2
print(gp)
## Warning: Removed 4 rows containing missing values (geom_errorbar).

dsp_models_cols <- c("id", 
                    glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
                    grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE)) 
# if (glb_is_classification && glb_is_binomial) 
#     dsp_models_cols <- c(dsp_models_cols, "opt.prob.threshold.OOB")
print(dsp_models_df <- orderBy(get_model_sel_frmla(), glb_models_df)[, dsp_models_cols])
##                           id max.Accuracy.OOB max.AUCROCR.OOB
## 3 Max.cor.Y.rcv.1X1###glmnet        0.4120735       0.6326125
## 5      Low.cor.X##rcv#glmnet        0.3805774       0.6326125
## 6          All.X##rcv#glmnet        0.3805774       0.6326125
## 7             All.X##rcv#glm        0.3805774       0.6265634
## 4       Max.cor.Y##rcv#rpart        0.3805774       0.6225015
## 1        MFO###myMFO_classfr        0.3805774       0.5000000
## 2  Random###myrandom_classfr        0.3805774       0.4456750
##   max.AUCpROC.OOB max.Accuracy.fit opt.prob.threshold.fit
## 3       0.6118498        0.7078431                    0.4
## 5       0.6212011        0.7105259                    0.4
## 6       0.6212011        0.7105259                    0.4
## 7       0.6091905        0.7046551                    0.4
## 4       0.6137639        0.7078962                    0.3
## 1       0.5000000        0.3862745                    0.3
## 2       0.4867621        0.3862745                    0.3
##   opt.prob.threshold.OOB
## 3                    0.2
## 5                    0.1
## 6                    0.1
## 7                    0.1
## 4                    0.2
## 1                    0.3
## 2                    0.3
# print(myplot_radar(radar_inp_df = dsp_models_df))
print("Metrics used for model selection:"); print(get_model_sel_frmla())
## [1] "Metrics used for model selection:"
## ~-max.Accuracy.OOB - max.AUCROCR.OOB - max.AUCpROC.OOB - max.Accuracy.fit - 
##     opt.prob.threshold.OOB
## <environment: 0x7f9fc6e794b0>
print(sprintf("Best model id: %s", dsp_models_df[1, "id"]))
## [1] "Best model id: Max.cor.Y.rcv.1X1###glmnet"
glb_get_predictions <- function(df, mdl_id, rsp_var, prob_threshold_def=NULL, verbose=FALSE) {
    mdl <- glb_models_lst[[mdl_id]]
    
    clmnNames <- mygetPredictIds(rsp_var, mdl_id)
    predct_var_name <- clmnNames$value        
    predct_prob_var_name <- clmnNames$prob
    predct_accurate_var_name <- clmnNames$is.acc
    predct_error_var_name <- clmnNames$err
    predct_erabs_var_name <- clmnNames$err.abs

    if (glb_is_regression) {
        df[, predct_var_name] <- predict(mdl, newdata=df, type="raw")
        if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_var_name) + 
                  facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
                  stat_smooth(method="glm"))

        df[, predct_error_var_name] <- df[, predct_var_name] - df[, glb_rsp_var]
        if (verbose) print(myplot_scatter(df, predct_var_name, predct_error_var_name) + 
                  #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
                  stat_smooth(method="auto"))
        if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_error_var_name) + 
                  #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
                  stat_smooth(method="glm"))
        
        df[, predct_erabs_var_name] <- abs(df[, predct_error_var_name])
        if (verbose) print(head(orderBy(reformulate(c("-", predct_erabs_var_name)), df)))
        
        df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])
    }

    if (glb_is_classification && glb_is_binomial) {
        prob_threshold <- glb_models_df[glb_models_df$id == mdl_id, 
                                        "opt.prob.threshold.OOB"]
        if (is.null(prob_threshold) || is.na(prob_threshold)) {
            warning("Using default probability threshold: ", prob_threshold_def)
            if (is.null(prob_threshold <- prob_threshold_def))
                stop("Default probability threshold is NULL")
        }
        
        df[, predct_prob_var_name] <- predict(mdl, newdata = df, type = "prob")[, 2]
        df[, predct_var_name] <- 
                factor(levels(df[, glb_rsp_var])[
                    (df[, predct_prob_var_name] >=
                        prob_threshold) * 1 + 1], levels(df[, glb_rsp_var]))
    
#         if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_var_name) + 
#                   facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
#                   stat_smooth(method="glm"))

        df[, predct_error_var_name] <- df[, predct_var_name] != df[, glb_rsp_var]
#         if (verbose) print(myplot_scatter(df, predct_var_name, predct_error_var_name) + 
#                   #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
#                   stat_smooth(method="auto"))
#         if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_error_var_name) + 
#                   #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
#                   stat_smooth(method="glm"))
        
        # if prediction is a TP (true +ve), measure distance from 1.0
        tp <- which((df[, predct_var_name] == df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[2]))
        df[tp, predct_erabs_var_name] <- abs(1 - df[tp, predct_prob_var_name])
        #rowIx <- which.max(df[tp, predct_erabs_var_name]); df[tp, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
        
        # if prediction is a TN (true -ve), measure distance from 0.0
        tn <- which((df[, predct_var_name] == df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[1]))
        df[tn, predct_erabs_var_name] <- abs(0 - df[tn, predct_prob_var_name])
        #rowIx <- which.max(df[tn, predct_erabs_var_name]); df[tn, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
        
        # if prediction is a FP (flse +ve), measure distance from 0.0
        fp <- which((df[, predct_var_name] != df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[2]))
        df[fp, predct_erabs_var_name] <- abs(0 - df[fp, predct_prob_var_name])
        #rowIx <- which.max(df[fp, predct_erabs_var_name]); df[fp, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
        
        # if prediction is a FN (flse -ve), measure distance from 1.0
        fn <- which((df[, predct_var_name] != df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[1]))
        df[fn, predct_erabs_var_name] <- abs(1 - df[fn, predct_prob_var_name])
        #rowIx <- which.max(df[fn, predct_erabs_var_name]); df[fn, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]

        
        if (verbose) print(head(orderBy(reformulate(c("-", predct_erabs_var_name)), df)))
        
        df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])
    }    
    
    if (glb_is_classification && !glb_is_binomial) {
        df[, predct_var_name] <- predict(mdl, newdata = df, type = "raw")
        probCls <- predict(mdl, newdata = df, type = "prob")        
        df[, predct_prob_var_name] <- NA
        for (cls in names(probCls)) {
            mask <- (df[, predct_var_name] == cls)
            df[mask, predct_prob_var_name] <- probCls[mask, cls]
        }    
        if (verbose) print(myplot_histogram(df, predct_prob_var_name, 
                                            fill_col_name = predct_var_name))
        if (verbose) print(myplot_histogram(df, predct_prob_var_name, 
                                            facet_frmla = paste0("~", glb_rsp_var)))
        
        df[, predct_error_var_name] <- df[, predct_var_name] != df[, glb_rsp_var]
        
        # if prediction is erroneous, measure predicted class prob from actual class prob
        df[, predct_erabs_var_name] <- 0
        for (cls in names(probCls)) {
            mask <- (df[, glb_rsp_var] == cls) & (df[, predct_error_var_name])
            df[mask, predct_erabs_var_name] <- probCls[mask, cls]
        }    

        df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])        
    }

    return(df)
}    

#stop(here"); glb2Sav(); glbObsAll <- savObsAll; glbObsTrn <- savObsTrn; glbObsFit <- savObsFit; glbObsOOB <- savObsOOB; sav_models_df <- glb_models_df; glb_models_df <- sav_models_df; glb_featsimp_df <- sav_featsimp_df    

myget_category_stats <- function(obs_df, mdl_id, label) {
    require(dplyr)
    require(lazyeval)
    
    predct_var_name <- mygetPredictIds(glb_rsp_var, mdl_id)$value        
    predct_error_var_name <- mygetPredictIds(glb_rsp_var, mdl_id)$err.abs
    
    if (!predct_var_name %in% names(obs_df))
        obs_df <- glb_get_predictions(obs_df, mdl_id, glb_rsp_var)
    
    tmp_obs_df <- obs_df[, c(glbFeatsCategory, glb_rsp_var, 
                             predct_var_name, predct_error_var_name)]
#     tmp_obs_df <- obs_df %>%
#         dplyr::select_(glbFeatsCategory, glb_rsp_var, predct_var_name, predct_error_var_name) 
    #dplyr::rename(startprice.log10.predict.RFE.X.glmnet.err=error_abs_OOB)
    names(tmp_obs_df)[length(names(tmp_obs_df))] <- paste0("err.abs.", label)
    
    ret_ctgry_df <- tmp_obs_df %>%
        dplyr::group_by_(glbFeatsCategory) %>%
        dplyr::summarise_(#interp(~sum(abs(var)), var=as.name(glb_rsp_var)), 
            interp(~sum(var), var=as.name(paste0("err.abs.", label))), 
            interp(~mean(var), var=as.name(paste0("err.abs.", label))),
            interp(~n()))
    names(ret_ctgry_df) <- c(glbFeatsCategory, 
                             #paste0(glb_rsp_var, ".abs.", label, ".sum"),
                             paste0("err.abs.", label, ".sum"),                             
                             paste0("err.abs.", label, ".mean"), 
                             paste0(".n.", label))
    ret_ctgry_df <- dplyr::ungroup(ret_ctgry_df)
    #colSums(ret_ctgry_df[, -grep(glbFeatsCategory, names(ret_ctgry_df))])
    
    return(ret_ctgry_df)    
}
#print(colSums((ctgry_df <- myget_category_stats(obs_df=glbObsFit, mdl_id="", label="fit"))[, -grep(glbFeatsCategory, names(ctgry_df))]))

if (!is.null(glb_mdl_ensemble)) {
    fit.models_2_chunk_df <- myadd_chunk(fit.models_2_chunk_df, 
                            paste0("fit.models_2_", mdl_id_pfx), major.inc = TRUE, 
                                                label.minor = "ensemble")
    
    mdl_id_pfx <- "Ensemble"

    if (#(glb_is_regression) | 
        ((glb_is_classification) & (!glb_is_binomial)))
        stop("Ensemble models not implemented yet for multinomial classification")
    
    mygetEnsembleAutoMdlIds <- function() {
        tmp_models_df <- orderBy(get_model_sel_frmla(), glb_models_df)
        row.names(tmp_models_df) <- tmp_models_df$id
        mdl_threshold_pos <- 
            min(which(grepl("MFO|Random|Baseline", tmp_models_df$id))) - 1
        mdlIds <- tmp_models_df$id[1:mdl_threshold_pos]
        return(mdlIds[!grepl("Ensemble", mdlIds)])
    }
    
    if (glb_mdl_ensemble == "auto") {
        glb_mdl_ensemble <- mygetEnsembleAutoMdlIds()
        mdl_id_pfx <- paste0(mdl_id_pfx, ".auto")        
    } else if (grepl("^%<d-%", glb_mdl_ensemble)) {
        glb_mdl_ensemble <- eval(parse(text =
                        str_trim(unlist(strsplit(glb_mdl_ensemble, "%<d-%"))[2])))
    }
    
    for (mdl_id in glb_mdl_ensemble) {
        if (!(mdl_id %in% names(glb_models_lst))) {
            warning("Model ", mdl_id, " in glb_model_ensemble not found !")
            next
        }
        glbObsFit <- glb_get_predictions(df = glbObsFit, mdl_id, glb_rsp_var)
        glbObsOOB <- glb_get_predictions(df = glbObsOOB, mdl_id, glb_rsp_var)
    }
    
#mdl_id_pfx <- "Ensemble.RFE"; mdlId <- paste0(mdl_id_pfx, ".glmnet")
#glb_mdl_ensemble <- gsub(mygetPredictIds$value, "", grep("RFE\\.X\\.(?!Interact)", row.names(glb_featsimp_df), perl = TRUE, value = TRUE), fixed = TRUE)
#varImp(glb_models_lst[[mdlId]])
    
#cor_df <- data.frame(cor=cor(glbObsFit[, glb_rsp_var], glbObsFit[, paste(mygetPredictIds$value, glb_mdl_ensemble)], use="pairwise.complete.obs"))
#glbObsFit <- glb_get_predictions(df=glbObsFit, "Ensemble.glmnet", glb_rsp_var);print(colSums((ctgry_df <- myget_category_stats(obs_df=glbObsFit, mdl_id="Ensemble.glmnet", label="fit"))[, -grep(glbFeatsCategory, names(ctgry_df))]))
    
    ### bid0_sp
    #  Better than MFO; models.n=28; min.RMSE.fit=0.0521233; err.abs.fit.sum=7.3631895
    #  old: Top x from auto; models.n= 5; min.RMSE.fit=0.06311047; err.abs.fit.sum=9.5937080
    #  RFE only ;       models.n=16; min.RMSE.fit=0.05148588; err.abs.fit.sum=7.2875091
    #  RFE subset only ;models.n= 5; min.RMSE.fit=0.06040702; err.abs.fit.sum=9.059088
    #  RFE subset only ;models.n= 9; min.RMSE.fit=0.05933167; err.abs.fit.sum=8.7421288
    #  RFE subset only ;models.n=15; min.RMSE.fit=0.0584607; err.abs.fit.sum=8.5902066
    #  RFE subset only ;models.n=17; min.RMSE.fit=0.05496899; err.abs.fit.sum=8.0170431
    #  RFE subset only ;models.n=18; min.RMSE.fit=0.05441577; err.abs.fit.sum=7.837223
    #  RFE subset only ;models.n=16; min.RMSE.fit=0.05441577; err.abs.fit.sum=7.837223
    ### bid0_sp
    ### bid1_sp
    # "auto"; err.abs.fit.sum=76.699774; min.RMSE.fit=0.2186429
    # "RFE.X.*"; err.abs.fit.sum=; min.RMSE.fit=0.221114
    ### bid1_sp

    indep_vars <- paste(mygetPredictIds(glb_rsp_var)$value, glb_mdl_ensemble, sep = "")
    if (glb_is_classification)
        indep_vars <- paste(indep_vars, ".prob", sep = "")
    # Some models in glb_mdl_ensemble might not be fitted e.g. RFE.X.Interact
    indep_vars <- intersect(indep_vars, names(glbObsFit))
    
#     indep_vars <- grep(mygetPredictIds(glb_rsp_var)$value, names(glbObsFit), fixed=TRUE, value=TRUE)
#     if (glb_is_regression)
#         indep_vars <- indep_vars[!grepl("(err\\.abs|accurate)$", indep_vars)]
#     if (glb_is_classification && glb_is_binomial)
#         indep_vars <- grep("prob$", indep_vars, value=TRUE) else
#         indep_vars <- indep_vars[!grepl("err$", indep_vars)]

    #rfe_fit_ens_results <- myrun_rfe(glbObsFit, indep_vars)
    
    for (method in c("glm", "glmnet")) {
        for (trainControlMethod in 
             c("boot", "boot632", "cv", "repeatedcv"
               #, "LOOCV" # tuneLength * nrow(fitDF)
               , "LGOCV", "adaptive_cv"
               #, "adaptive_boot"  #error: adaptive$min should be less than 3 
               #, "adaptive_LGOCV" #error: adaptive$min should be less than 3 
               )) {
            #sav_models_df <- glb_models_df; all.equal(sav_models_df, glb_models_df)
            #glb_models_df <- sav_models_df; print(glb_models_df$id)
                
            if ((method == "glm") && (trainControlMethod != "repeatedcv"))
                # glm used only to identify outliers
                next
            
            ret_lst <- myfit_mdl(
                mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                    id.prefix = paste0(mdl_id_pfx, ".", trainControlMethod), 
                    type = glb_model_type, tune.df = NULL,
                    trainControl.method = trainControlMethod,
                    trainControl.number = glb_rcv_n_folds,
                    trainControl.repeats = glb_rcv_n_repeats,
                    trainControl.classProbs = glb_is_classification,
                    trainControl.summaryFunction = glbMdlMetricSummaryFn,
                    train.metric = glbMdlMetricSummary, 
                    train.maximize = glbMdlMetricMaximize,    
                    train.method = method)),
                indep_vars = indep_vars, rsp_var = glb_rsp_var, 
                fit_df = glbObsFit, OOB_df = glbObsOOB)
        }
    }
    dsp_models_df <- get_dsp_models_df()
}

if (is.null(glb_sel_mdl_id)) 
    glb_sel_mdl_id <- dsp_models_df[1, "id"] else 
    print(sprintf("User specified selection: %s", glb_sel_mdl_id))   
## [1] "User specified selection: All.X##rcv#glmnet"
myprint_mdl(glb_sel_mdl <- glb_models_lst[[glb_sel_mdl_id]])

##             Length Class      Mode     
## a0           62    -none-     numeric  
## beta        310    dgCMatrix  S4       
## df           62    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       62    -none-     numeric  
## dev.ratio    62    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## classnames    2    -none-     character
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames        5    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     2    -none-     character
## [1] "min lambda > lambdaOpt:"
##  (Intercept)       .rnorm Pclass.fctr2 Pclass.fctr3 
##   0.58568143  -0.04942397  -0.54820395  -1.80986086 
## [1] "max lambda < lambdaOpt:"
##  (Intercept)       .rnorm Pclass.fctr2 Pclass.fctr3 
##   0.60259812  -0.05186662  -0.57076451  -1.83424841
## [1] TRUE
# From here to save(), this should all be in one function
#   these are executed in the same seq twice more:
#       fit.data.training & predict.data.new chunks
print(sprintf("%s fit prediction diagnostics:", glb_sel_mdl_id))
## [1] "All.X##rcv#glmnet fit prediction diagnostics:"
glbObsFit <- glb_get_predictions(df = glbObsFit, mdl_id = glb_sel_mdl_id, 
                                 rsp_var = glb_rsp_var)
print(sprintf("%s OOB prediction diagnostics:", glb_sel_mdl_id))
## [1] "All.X##rcv#glmnet OOB prediction diagnostics:"
glbObsOOB <- glb_get_predictions(df = glbObsOOB, mdl_id = glb_sel_mdl_id, 
                                     rsp_var = glb_rsp_var)

print(glb_featsimp_df <- myget_feats_importance(mdl = glb_sel_mdl, featsimp_df = NULL))
##              All.X..rcv.glmnet.imp       imp
## Pclass.fctr3             100.00000 100.00000
## Pclass.fctr2              30.82280  30.82280
## .rnorm                     2.79322   2.79322
## .pos                       0.00000   0.00000
## PassengerId                0.00000   0.00000
#mdl_id <-"RFE.X.glmnet"; glb_featsimp_df <- myget_feats_importance(glb_models_lst[[mdl_id]], glb_featsimp_df); glb_featsimp_df[, paste0(mdl_id, ".imp")] <- glb_featsimp_df$imp; print(glb_featsimp_df)
#print(head(sbst_featsimp_df <- subset(glb_featsimp_df, is.na(RFE.X.glmnet.imp) | (abs(RFE.X.YeoJohnson.glmnet.imp - RFE.X.glmnet.imp) > 0.0001), select=-imp)))
#print(orderBy(~ -cor.y.abs, subset(glb_feats_df, id %in% c(row.names(sbst_featsimp_df), "startprice.dcm1.is9", "D.weight.post.stop.sum"))))

# Used again in fit.data.training & predict.data.new chunks
glb_analytics_diag_plots <- function(obs_df, mdl_id, prob_threshold=NULL) {
    if (!is.null(featsimp_df <- glb_featsimp_df)) {
        featsimp_df$feat <- gsub("`(.*?)`", "\\1", row.names(featsimp_df))    
        featsimp_df$feat.interact <- gsub("(.*?):(.*)", "\\2", featsimp_df$feat)
        featsimp_df$feat <- gsub("(.*?):(.*)", "\\1", featsimp_df$feat)    
        featsimp_df$feat.interact <- 
            ifelse(featsimp_df$feat.interact == featsimp_df$feat, 
                                            NA, featsimp_df$feat.interact)
        featsimp_df$feat <- 
            gsub("(.*?)\\.fctr(.*)", "\\1\\.fctr", featsimp_df$feat)
        featsimp_df$feat.interact <- 
            gsub("(.*?)\\.fctr(.*)", "\\1\\.fctr", featsimp_df$feat.interact) 
        featsimp_df <- orderBy(~ -imp.max, 
            summaryBy(imp ~ feat + feat.interact, data=featsimp_df,
                      FUN=max))    
        #rex_str=":(.*)"; txt_vctr=tail(featsimp_df$feat); ret_lst <- regexec(rex_str, txt_vctr); ret_lst <- regmatches(txt_vctr, ret_lst); ret_vctr <- sapply(1:length(ret_lst), function(pos_ix) ifelse(length(ret_lst[[pos_ix]]) > 0, ret_lst[[pos_ix]], "")); print(ret_vctr <- ret_vctr[ret_vctr != ""])    
        
        featsimp_df <- subset(featsimp_df, !is.na(imp.max))
        if (nrow(featsimp_df) > 5) {
            warning("Limiting important feature scatter plots to 5 out of ",
                    nrow(featsimp_df))
            featsimp_df <- head(featsimp_df, 5)
        }
        
    #     if (!all(is.na(featsimp_df$feat.interact)))
    #         stop("not implemented yet")
        rsp_var_out <- mygetPredictIds(glb_rsp_var, mdl_id)$value
        for (var in featsimp_df$feat) {
            plot_df <- melt(obs_df, id.vars = var, 
                            measure.vars = c(glb_rsp_var, rsp_var_out))
    
            print(myplot_scatter(plot_df, var, "value", colorcol_name = "variable",
                                facet_colcol_name = "variable", jitter = TRUE) + 
                          guides(color = FALSE))
        }
    }
    
    if (glb_is_regression) {
        if (is.null(featsimp_df) || (nrow(featsimp_df) == 0))
            warning("No important features in glb_fin_mdl") else
            print(myplot_prediction_regression(df=obs_df, 
                        feat_x=ifelse(nrow(featsimp_df) > 1, featsimp_df$feat[2],
                                      ".rownames"), 
                                               feat_y=featsimp_df$feat[1],
                        rsp_var=glb_rsp_var, rsp_var_out=rsp_var_out,
                        id_vars=glbFeatsId)
    #               + facet_wrap(reformulate(featsimp_df$feat[2])) # if [1 or 2] is a factor
    #               + geom_point(aes_string(color="<col_name>.fctr")) #  to color the plot
                  )
    }    
    
    if (glb_is_classification) {
        if (is.null(featsimp_df) || (nrow(featsimp_df) == 0))
            warning("No features in selected model are statistically important")
        else print(myplot_prediction_classification(df = obs_df, 
                                feat_x = ifelse(nrow(featsimp_df) > 1, 
                                                featsimp_df$feat[2], ".rownames"),
                                               feat_y = featsimp_df$feat[1],
                                                rsp_var = glb_rsp_var, 
                                                rsp_var_out = rsp_var_out, 
                                                id_vars = glbFeatsId,
                                                prob_threshold = prob_threshold))
    }    
}

if (glb_is_classification && glb_is_binomial)
    glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id, 
            prob_threshold = glb_models_df[glb_models_df$id == glb_sel_mdl_id, 
                                           "opt.prob.threshold.OOB"]) else
    glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id)                  

## [1] "Min/Max Boundaries: "
##   PassengerId Survived.fctr Survived.fctr.All.X..rcv.glmnet.prob
## 1         645             Y                            0.1959565
## 2         179             N                            0.5380615
##   Survived.fctr.All.X..rcv.glmnet Survived.fctr.All.X..rcv.glmnet.err
## 1                               Y                               FALSE
## 2                               Y                                TRUE
##   Survived.fctr.All.X..rcv.glmnet.err.abs
## 1                               0.8040435
## 2                               0.5380615
##   Survived.fctr.All.X..rcv.glmnet.is.acc
## 1                                   TRUE
## 2                                  FALSE
##   Survived.fctr.All.X..rcv.glmnet.accurate
## 1                                     TRUE
## 2                                    FALSE
##   Survived.fctr.All.X..rcv.glmnet.error .label
## 1                             0.0000000    645
## 2                             0.4380615    179
## [1] "Inaccurate: "
##   PassengerId Survived.fctr Survived.fctr.All.X..rcv.glmnet.prob
## 1         621             N                            0.2066332
## 2         281             N                            0.2074517
## 3         566             N                            0.2097007
## 4         651             N                            0.2104961
## 5         350             N                            0.2107614
## 6         412             N                            0.2110992
##   Survived.fctr.All.X..rcv.glmnet Survived.fctr.All.X..rcv.glmnet.err
## 1                               Y                                TRUE
## 2                               Y                                TRUE
## 3                               Y                                TRUE
## 4                               Y                                TRUE
## 5                               Y                                TRUE
## 6                               Y                                TRUE
##   Survived.fctr.All.X..rcv.glmnet.err.abs
## 1                               0.2066332
## 2                               0.2074517
## 3                               0.2097007
## 4                               0.2104961
## 5                               0.2107614
## 6                               0.2110992
##   Survived.fctr.All.X..rcv.glmnet.is.acc
## 1                                  FALSE
## 2                                  FALSE
## 3                                  FALSE
## 4                                  FALSE
## 5                                  FALSE
## 6                                  FALSE
##   Survived.fctr.All.X..rcv.glmnet.accurate
## 1                                    FALSE
## 2                                    FALSE
## 3                                    FALSE
## 4                                    FALSE
## 5                                    FALSE
## 6                                    FALSE
##   Survived.fctr.All.X..rcv.glmnet.error
## 1                             0.1066332
## 2                             0.1074517
## 3                             0.1097007
## 4                             0.1104961
## 5                             0.1107614
## 6                             0.1110992
##     PassengerId Survived.fctr Survived.fctr.All.X..rcv.glmnet.prob
## 13          153             N                            0.2144510
## 37          740             N                            0.2208194
## 65          793             N                            0.2249255
## 91          848             N                            0.2287886
## 164         667             N                            0.5025091
## 198         823             N                            0.6257660
##     Survived.fctr.All.X..rcv.glmnet Survived.fctr.All.X..rcv.glmnet.err
## 13                                Y                                TRUE
## 37                                Y                                TRUE
## 65                                Y                                TRUE
## 91                                Y                                TRUE
## 164                               Y                                TRUE
## 198                               Y                                TRUE
##     Survived.fctr.All.X..rcv.glmnet.err.abs
## 13                                0.2144510
## 37                                0.2208194
## 65                                0.2249255
## 91                                0.2287886
## 164                               0.5025091
## 198                               0.6257660
##     Survived.fctr.All.X..rcv.glmnet.is.acc
## 13                                   FALSE
## 37                                   FALSE
## 65                                   FALSE
## 91                                   FALSE
## 164                                  FALSE
## 198                                  FALSE
##     Survived.fctr.All.X..rcv.glmnet.accurate
## 13                                     FALSE
## 37                                     FALSE
## 65                                     FALSE
## 91                                     FALSE
## 164                                    FALSE
## 198                                    FALSE
##     Survived.fctr.All.X..rcv.glmnet.error
## 13                              0.1144510
## 37                              0.1208194
## 65                              0.1249255
## 91                              0.1287886
## 164                             0.4025091
## 198                             0.5257660
##     PassengerId Survived.fctr Survived.fctr.All.X..rcv.glmnet.prob
## 231         298             N                            0.6541874
## 232         119             N                            0.6554764
## 233         333             N                            0.6585039
## 234         175             N                            0.6602668
## 235         660             N                            0.6603878
## 236         138             N                            0.6640689
##     Survived.fctr.All.X..rcv.glmnet Survived.fctr.All.X..rcv.glmnet.err
## 231                               Y                                TRUE
## 232                               Y                                TRUE
## 233                               Y                                TRUE
## 234                               Y                                TRUE
## 235                               Y                                TRUE
## 236                               Y                                TRUE
##     Survived.fctr.All.X..rcv.glmnet.err.abs
## 231                               0.6541874
## 232                               0.6554764
## 233                               0.6585039
## 234                               0.6602668
## 235                               0.6603878
## 236                               0.6640689
##     Survived.fctr.All.X..rcv.glmnet.is.acc
## 231                                  FALSE
## 232                                  FALSE
## 233                                  FALSE
## 234                                  FALSE
## 235                                  FALSE
## 236                                  FALSE
##     Survived.fctr.All.X..rcv.glmnet.accurate
## 231                                    FALSE
## 232                                    FALSE
## 233                                    FALSE
## 234                                    FALSE
## 235                                    FALSE
## 236                                    FALSE
##     Survived.fctr.All.X..rcv.glmnet.error
## 231                             0.5541874
## 232                             0.5554764
## 233                             0.5585039
## 234                             0.5602668
## 235                             0.5603878
## 236                             0.5640689

if (!is.null(glbFeatsCategory)) {
    glbLvlCategory <- merge(glbLvlCategory, 
            myget_category_stats(obs_df = glbObsFit, mdl_id = glb_sel_mdl_id, 
                                 label = "fit"), 
                            by = glbFeatsCategory, all = TRUE)
    row.names(glbLvlCategory) <- glbLvlCategory[, glbFeatsCategory]
    glbLvlCategory <- merge(glbLvlCategory, 
            myget_category_stats(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id,
                                 label="OOB"),
                          #by=glbFeatsCategory, all=TRUE) glb_ctgry-df already contains .n.OOB ?
                          all = TRUE)
    row.names(glbLvlCategory) <- glbLvlCategory[, glbFeatsCategory]
    if (any(grepl("OOB", glbMdlMetricsEval)))
        print(orderBy(~-err.abs.OOB.mean, glbLvlCategory)) else
            print(orderBy(~-err.abs.fit.mean, glbLvlCategory))
    print(colSums(glbLvlCategory[, -grep(glbFeatsCategory, names(glbLvlCategory))]))
}
##   Pclass.fctr .n.OOB .n.Fit .n.Tst .freqRatio.Fit .freqRatio.OOB
## 2           2     88     96     93      0.1882353      0.2309711
## 1           1     86    130    107      0.2549020      0.2257218
## 3           3    207    284    218      0.5568627      0.5433071
##   .freqRatio.Tst err.abs.fit.sum err.abs.fit.mean .n.fit err.abs.OOB.sum
## 2      0.2224880        47.72973        0.4971847     96        43.79759
## 1      0.2559809        57.64010        0.4433854    130        42.06919
## 3      0.5215311        97.24814        0.3424230    284        79.20811
##   err.abs.OOB.mean
## 2        0.4976999
## 1        0.4891767
## 3        0.3826479
##           .n.OOB           .n.Fit           .n.Tst   .freqRatio.Fit 
##       381.000000       510.000000       418.000000         1.000000 
##   .freqRatio.OOB   .freqRatio.Tst  err.abs.fit.sum err.abs.fit.mean 
##         1.000000         1.000000       202.617974         1.282993 
##           .n.fit  err.abs.OOB.sum err.abs.OOB.mean 
##       510.000000       165.074900         1.369524
write.csv(glbObsOOB[, c(glbFeatsId, 
                grep(glb_rsp_var, names(glbObsOOB), fixed=TRUE, value=TRUE))], 
    paste0(gsub(".", "_", paste0(glbOut$pfx, glb_sel_mdl_id), fixed=TRUE), 
           "_OOBobs.csv"), row.names=FALSE)

fit.models_2_chunk_df <- 
    myadd_chunk(NULL, "fit.models_2_bgn", label.minor = "teardown")
##              label step_major step_minor label_minor    bgn end elapsed
## 1 fit.models_2_bgn          1          0    teardown 72.168  NA      NA
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc=FALSE)
##         label step_major step_minor label_minor    bgn   end elapsed
## 18 fit.models          8          2           2 62.676 72.18   9.504
## 19 fit.models          8          3           3 72.181    NA      NA
# if (sum(is.na(glbObsAll$D.P.http)) > 0)
#         stop("fit.models_3: Why is this happening ?")

#stop(here"); glb2Sav()
sync_glb_obs_df <- function() {
    # Merge or cbind ?
    for (col in setdiff(names(glbObsFit), names(glbObsTrn)))
        glbObsTrn[glbObsTrn$.lcn == "Fit", col] <<- glbObsFit[, col]
    for (col in setdiff(names(glbObsFit), names(glbObsAll)))
        glbObsAll[glbObsAll$.lcn == "Fit", col] <<- glbObsFit[, col]
    if (all(is.na(glbObsNew[, glb_rsp_var])))
        for (col in setdiff(names(glbObsOOB), names(glbObsTrn)))
            glbObsTrn[glbObsTrn$.lcn == "OOB", col] <<- glbObsOOB[, col]
    for (col in setdiff(names(glbObsOOB), names(glbObsAll)))
        glbObsAll[glbObsAll$.lcn == "OOB", col] <<- glbObsOOB[, col]
}
sync_glb_obs_df()
    
print(setdiff(names(glbObsNew), names(glbObsAll)))
## character(0)
replay.petrisim(pn=glb_analytics_pn, 
    replay.trans=(glb_analytics_avl_objs <- c(glb_analytics_avl_objs, 
        "model.selected")), flip_coord=TRUE)
## time trans    "bgn " "fit.data.training.all " "predict.data.new " "end " 
## 0.0000   multiple enabled transitions:  data.training.all data.new model.selected    firing:  data.training.all 
## 1.0000    1   2 1 0 0 
## 1.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction   firing:  data.new 
## 2.0000    2   1 1 1 0 
## 2.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction data.new.prediction   firing:  model.selected 
## 3.0000    3   0 2 1 0

glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.data.training", major.inc = TRUE)
##                label step_major step_minor label_minor    bgn    end
## 19        fit.models          8          3           3 72.181 75.789
## 20 fit.data.training          9          0           0 75.789     NA
##    elapsed
## 19   3.608
## 20      NA

Step 9.0: fit data training

#load(paste0(glb_inp_pfx, "dsk.RData"))

if (!is.null(glb_fin_mdl_id) && (glb_fin_mdl_id %in% names(glb_models_lst))) {
    warning("Final model same as user selected model")
    glb_fin_mdl <- glb_models_lst[[glb_fin_mdl_id]]
} else 
# if (nrow(glbObsFit) + length(glbObsFitOutliers) == nrow(glbObsTrn))
if (!all(is.na(glbObsNew[, glb_rsp_var])))
{    
    warning("Final model same as glb_sel_mdl_id")
    glb_fin_mdl_id <- paste0("Final.", glb_sel_mdl_id)
    glb_fin_mdl <- glb_sel_mdl
    glb_models_lst[[glb_fin_mdl_id]] <- glb_fin_mdl
} else {    
            if (grepl("RFE\\.X", names(glbMdlFamilies))) {
                indep_vars <- myadjust_interaction_feats(subset(glb_feats_df, 
                                                    !nzv & (exclude.as.feat != 1))[, "id"])
                rfe_trn_results <- 
                    myrun_rfe(glbObsTrn, indep_vars, glbRFESizes[["Final"]])
                if (!isTRUE(all.equal(sort(predictors(rfe_trn_results)),
                                      sort(predictors(rfe_fit_results))))) {
                    print("Diffs predictors(rfe_trn_results) vs. predictors(rfe_fit_results):")
                    print(setdiff(predictors(rfe_trn_results), predictors(rfe_fit_results)))
                    print("Diffs predictors(rfe_fit_results) vs. predictors(rfe_trn_results):")
                    print(setdiff(predictors(rfe_fit_results), predictors(rfe_trn_results)))
            }
        }
    # }    

    if (grepl("Ensemble", glb_sel_mdl_id)) {
        # Find which models are relevant
        mdlimp_df <- subset(myget_feats_importance(glb_sel_mdl), imp > 5)
        # Fit selected models on glbObsTrn
        for (mdl_id in gsub(".prob", "", 
gsub(mygetPredictIds(glb_rsp_var)$value, "", row.names(mdlimp_df), fixed = TRUE),
                            fixed = TRUE)) {
            mdl_id_components <- unlist(strsplit(mdl_id, "[.]"))
            mdlIdPfx <- paste0(c(head(mdl_id_components, -1), "Train"), 
                               collapse = ".")
            if (grepl("RFE\\.X\\.", mdlIdPfx)) 
                mdlIndepVars <- myadjust_interaction_feats(myextract_actual_feats(
                    predictors(rfe_trn_results))) else
                mdlIndepVars <- trim(unlist(
            strsplit(glb_models_df[glb_models_df$id == mdl_id, "feats"], "[,]")))
            ret_lst <- 
                myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                        id.prefix = mdlIdPfx, 
                        type = glb_model_type, tune.df = glbMdlTuneParams,
                        trainControl.method = "repeatedcv",
                        trainControl.number = glb_rcv_n_folds,
                        trainControl.repeats = glb_rcv_n_repeats,
                        trainControl.classProbs = glb_is_classification,
                        trainControl.summaryFunction = glbMdlMetricSummaryFn,
                        train.metric = glbMdlMetricSummary, 
                        train.maximize = glbMdlMetricMaximize,    
                        train.method = tail(mdl_id_components, 1))),
                    indep_vars = mdlIndepVars,
                    rsp_var = glb_rsp_var, 
                    fit_df = glbObsTrn, OOB_df = NULL)
            
            glbObsTrn <- glb_get_predictions(df = glbObsTrn,
                                                mdl_id = tail(glb_models_df$id, 1), 
                                                rsp_var = glb_rsp_var,
                                                prob_threshold_def = 
                    subset(glb_models_df, id == mdl_id)$opt.prob.threshold.OOB)
            glbObsNew <- glb_get_predictions(df = glbObsNew,
                                                mdl_id = tail(glb_models_df$id, 1), 
                                                rsp_var = glb_rsp_var,
                                                prob_threshold_def = 
                    subset(glb_models_df, id == mdl_id)$opt.prob.threshold.OOB)
        }    
    }
    
    # "Final" model
    if ((model_method <- glb_sel_mdl$method) == "custom")
        # get actual method from the mdl_id
        model_method <- tail(unlist(strsplit(glb_sel_mdl_id, "[.]")), 1)
        
    if (grepl("Ensemble", glb_sel_mdl_id)) {
        # Find which models are relevant
        mdlimp_df <- subset(myget_feats_importance(glb_sel_mdl), imp > 5)
        if (glb_is_classification && glb_is_binomial)
            indep_vars_vctr <- gsub("(.*)\\.(.*)\\.prob", "\\1\\.Train\\.\\2\\.prob",
                                    row.names(mdlimp_df)) else
            indep_vars_vctr <- gsub("(.*)\\.(.*)", "\\1\\.Train\\.\\2",
                                    row.names(mdlimp_df))
    } else 
    if (grepl("RFE.X", glb_sel_mdl_id, fixed = TRUE)) {
        indep_vars_vctr <- myextract_actual_feats(predictors(rfe_trn_results))
    } else indep_vars_vctr <- 
                trim(unlist(strsplit(glb_models_df[glb_models_df$id ==
                                                   glb_sel_mdl_id
                                                   , "feats"], "[,]")))
        
    if (!is.null(glb_preproc_methods) &&
        ((match_pos <- regexpr(gsub(".", "\\.", 
                                    paste(glb_preproc_methods, collapse = "|"),
                                   fixed = TRUE), glb_sel_mdl_id)) != -1))
        ths_preProcess <- str_sub(glb_sel_mdl_id, match_pos, 
                                match_pos + attr(match_pos, "match.length") - 1) else
        ths_preProcess <- NULL                                      

    mdl_id_pfx <- ifelse(grepl("Ensemble", glb_sel_mdl_id),
                                   "Final.Ensemble", "Final")
    
    trnobs_df <- glbObsTrn 
    if (!is.null(glbObsTrnOutliers[[mdl_id_pfx]])) {
        trnobs_df <- glbObsTrn[!(glbObsTrn[, glbFeatsId] %in% glbObsTrnOutliers[[mdl_id_pfx]]), ]
        print(sprintf("Outliers removed: %d", nrow(glbObsTrn) - nrow(trnobs_df)))
        print(setdiff(glbObsTrn[, glbFeatsId], trnobs_df[, glbFeatsId]))
    }    
        
    # Force fitting of Final.glm to identify outliers
    method_vctr <- unique(c(myparseMdlId(glb_sel_mdl_id)$alg, glbMdlFamilies[["Final"]]))
    for (method in method_vctr) {
        #source("caret_nominalTrainWorkflow.R")
        
        # glmnet requires at least 2 indep vars
        if ((length(indep_vars_vctr) == 1) && (method %in% "glmnet"))
            next
        
        ret_lst <- 
            myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                    id.prefix = mdl_id_pfx, 
                    type = glb_model_type, trainControl.method = "repeatedcv",
                    trainControl.number = glb_rcv_n_folds, 
                    trainControl.repeats = glb_rcv_n_repeats,
                    trainControl.classProbs = glb_is_classification,
                    trainControl.summaryFunction = glbMdlMetricSummaryFn,
                    trainControl.allowParallel = glbMdlAllowParallel,
                    train.metric = glbMdlMetricSummary, 
                    train.maximize = glbMdlMetricMaximize,    
                    train.method = method,
                    train.preProcess = ths_preProcess)),
                indep_vars = indep_vars_vctr, rsp_var = glb_rsp_var, 
                fit_df = trnobs_df, OOB_df = NULL)
        
        if ((length(method_vctr) == 1) || (method != "glm")) {
            glb_fin_mdl <- glb_models_lst[[length(glb_models_lst)]] 
            glb_fin_mdl_id <- glb_models_df[length(glb_models_lst), "id"]
        }
    }
        
}
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Final##rcv#glmnet"
## [1] "    indep_vars: .pos,PassengerId,.rnorm,Pclass.fctr"
## [1] "myfit_mdl: setup complete: 1.066000 secs"
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 0.1, lambda = 0.0146 on full training set
## [1] "myfit_mdl: train complete: 3.256000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = mdl_id_pfx, : model's bestTune found at an extreme of
## tuneGrid for parameter: alpha

##             Length Class      Mode     
## a0           69    -none-     numeric  
## beta        345    dgCMatrix  S4       
## df           69    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       69    -none-     numeric  
## dev.ratio    69    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## classnames    2    -none-     character
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames        5    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     2    -none-     character
## [1] "min lambda > lambdaOpt:"
##   (Intercept)          .pos        .rnorm   PassengerId  Pclass.fctr2 
##  4.446684e-01 -5.040058e-05 -9.899312e-02 -4.648318e-05 -4.752877e-01 
##  Pclass.fctr3 
## -1.490167e+00 
## [1] "max lambda < lambdaOpt:"
##   (Intercept)          .pos        .rnorm   PassengerId  Pclass.fctr2 
##  4.563697e-01 -5.224751e-05 -1.001568e-01 -4.817843e-05 -4.877534e-01 
##  Pclass.fctr3 
## -1.504855e+00 
## [1] "myfit_mdl: train diagnostics complete: 3.804000 secs"

##          Prediction
## Reference   N   Y
##         N 373 176
##         Y 119 223
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   0.6689113356   0.3213663297   0.6369296583   0.6997712810   0.6161616162 
## AccuracyPValue  McnemarPValue 
##   0.0006157297   0.0011123713 
## [1] "myfit_mdl: predict complete: 5.046000 secs"
##                  id                               feats max.nTuningRuns
## 1 Final##rcv#glmnet .pos,PassengerId,.rnorm,Pclass.fctr              20
##   min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1                      2.185                 0.017       0.6488592
##   max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1    0.8269581    0.4707602       0.6895578                    0.4
##   max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1       0.6018893        0.6887392             0.6369297
##   max.AccuracyUpper.fit max.Kappa.fit max.AccuracySD.fit max.KappaSD.fit
## 1             0.6997713     0.3097279         0.02683647      0.06772965
## [1] "myfit_mdl: exit: 5.063000 secs"
rm(ret_lst)
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.data.training", major.inc=FALSE)
##                label step_major step_minor label_minor    bgn    end
## 20 fit.data.training          9          0           0 75.789 81.327
## 21 fit.data.training          9          1           1 81.328     NA
##    elapsed
## 20   5.538
## 21      NA
#stop(here"); glb2Sav()
if (glb_is_classification && glb_is_binomial) 
    prob_threshold <- glb_models_df[glb_models_df$id == glb_sel_mdl_id,
                                        "opt.prob.threshold.OOB"] else 
    prob_threshold <- NULL

if (grepl("Ensemble", glb_fin_mdl_id)) {
    # Get predictions for each model in ensemble; Outliers that have been moved to OOB might not have been predicted yet
    mdlEnsembleComps <- unlist(str_split(subset(glb_models_df, 
                                                id == glb_fin_mdl_id)$feats, ","))
    if (glb_is_classification && glb_is_binomial)
        mdlEnsembleComps <- gsub("\\.prob$", "", mdlEnsembleComps)
    mdlEnsembleComps <- gsub(paste0("^", 
                        gsub(".", "\\.", mygetPredictIds(glb_rsp_var)$value, fixed = TRUE)),
                             "", mdlEnsembleComps)
    for (mdl_id in mdlEnsembleComps) {
        glbObsTrn <- glb_get_predictions(df = glbObsTrn, mdl_id = mdl_id, 
                                            rsp_var = glb_rsp_var,
                                            prob_threshold_def = prob_threshold)
        glbObsNew <- glb_get_predictions(df = glbObsNew, mdl_id = mdl_id, 
                                            rsp_var = glb_rsp_var,
                                            prob_threshold_def = prob_threshold)
    }    
}
glbObsTrn <- glb_get_predictions(df = glbObsTrn, mdl_id = glb_fin_mdl_id, 
                                     rsp_var = glb_rsp_var,
                                    prob_threshold_def = prob_threshold)
## Warning in glb_get_predictions(df = glbObsTrn, mdl_id = glb_fin_mdl_id, :
## Using default probability threshold: 0.1
glb_featsimp_df <- myget_feats_importance(mdl=glb_fin_mdl,
                                          featsimp_df=glb_featsimp_df)
#glb_featsimp_df[, paste0(glb_fin_mdl_id, ".imp")] <- glb_featsimp_df$imp
print(glb_featsimp_df)
##              All.X..rcv.glmnet.imp Final..rcv.glmnet.imp          imp
## Pclass.fctr3             100.00000          1.000000e+02 1.000000e+02
## Pclass.fctr2              30.82280          3.205381e+01 3.205381e+01
## .rnorm                     2.79322          6.644042e+00 6.644042e+00
## .pos                       0.00000          2.652313e-04 2.652313e-04
## PassengerId                0.00000          0.000000e+00 0.000000e+00
if (glb_is_classification && glb_is_binomial)
    glb_analytics_diag_plots(obs_df=glbObsTrn, mdl_id=glb_fin_mdl_id, 
            prob_threshold=glb_models_df[glb_models_df$id == glb_sel_mdl_id, 
                                         "opt.prob.threshold.OOB"]) else
    glb_analytics_diag_plots(obs_df=glbObsTrn, mdl_id=glb_fin_mdl_id)                  

## [1] "Min/Max Boundaries: "
##   PassengerId Survived.fctr Survived.fctr.All.X..rcv.glmnet.prob
## 1         842             N                            0.4621856
## 2         656             N                            0.5401453
##   Survived.fctr.All.X..rcv.glmnet Survived.fctr.All.X..rcv.glmnet.err
## 1                               Y                                TRUE
## 2                               Y                                TRUE
##   Survived.fctr.All.X..rcv.glmnet.err.abs
## 1                               0.4621856
## 2                               0.5401453
##   Survived.fctr.All.X..rcv.glmnet.is.acc
## 1                                  FALSE
## 2                                  FALSE
##   Survived.fctr.Final..rcv.glmnet.prob Survived.fctr.Final..rcv.glmnet
## 1                            0.3835251                               Y
## 2                            0.5380414                               Y
##   Survived.fctr.Final..rcv.glmnet.err
## 1                                TRUE
## 2                                TRUE
##   Survived.fctr.Final..rcv.glmnet.err.abs
## 1                               0.3835251
## 2                               0.5380414
##   Survived.fctr.Final..rcv.glmnet.is.acc
## 1                                  FALSE
## 2                                  FALSE
##   Survived.fctr.Final..rcv.glmnet.accurate
## 1                                    FALSE
## 2                                    FALSE
##   Survived.fctr.Final..rcv.glmnet.error .label
## 1                             0.2835251    842
## 2                             0.4380414    656
## [1] "Inaccurate: "
##   PassengerId Survived.fctr Survived.fctr.All.X..rcv.glmnet.prob
## 1         105             N                            0.1972914
## 2         885             N                            0.2073033
## 3         621             N                                   NA
## 4         684             N                            0.2097946
## 5         353             N                            0.2078765
## 6         566             N                                   NA
##   Survived.fctr.All.X..rcv.glmnet Survived.fctr.All.X..rcv.glmnet.err
## 1                               Y                                TRUE
## 2                               Y                                TRUE
## 3                            <NA>                                  NA
## 4                               Y                                TRUE
## 5                               Y                                TRUE
## 6                            <NA>                                  NA
##   Survived.fctr.All.X..rcv.glmnet.err.abs
## 1                               0.1972914
## 2                               0.2073033
## 3                                      NA
## 4                               0.2097946
## 5                               0.2078765
## 6                                      NA
##   Survived.fctr.All.X..rcv.glmnet.is.acc
## 1                                  FALSE
## 2                                  FALSE
## 3                                     NA
## 4                                  FALSE
## 5                                  FALSE
## 6                                     NA
##   Survived.fctr.Final..rcv.glmnet.prob Survived.fctr.Final..rcv.glmnet
## 1                            0.1983866                               Y
## 2                            0.2055559                               Y
## 3                            0.2084962                               Y
## 4                            0.2136906                               Y
## 5                            0.2153437                               Y
## 6                            0.2154529                               Y
##   Survived.fctr.Final..rcv.glmnet.err
## 1                                TRUE
## 2                                TRUE
## 3                                TRUE
## 4                                TRUE
## 5                                TRUE
## 6                                TRUE
##   Survived.fctr.Final..rcv.glmnet.err.abs
## 1                               0.1983866
## 2                               0.2055559
## 3                               0.2084962
## 4                               0.2136906
## 5                               0.2153437
## 6                               0.2154529
##   Survived.fctr.Final..rcv.glmnet.is.acc
## 1                                  FALSE
## 2                                  FALSE
## 3                                  FALSE
## 4                                  FALSE
## 5                                  FALSE
## 6                                  FALSE
##   Survived.fctr.Final..rcv.glmnet.accurate
## 1                                    FALSE
## 2                                    FALSE
## 3                                    FALSE
## 4                                    FALSE
## 5                                    FALSE
## 6                                    FALSE
##   Survived.fctr.Final..rcv.glmnet.error
## 1                            0.09838665
## 2                            0.10555587
## 3                            0.10849617
## 4                            0.11369064
## 5                            0.11534371
## 6                            0.11545291
##     PassengerId Survived.fctr Survived.fctr.All.X..rcv.glmnet.prob
## 8           281             N                                   NA
## 139         236             N                                   NA
## 201         687             N                                   NA
## 263         653             N                            0.2333403
## 280         475             N                                   NA
## 395         552             N                                   NA
##     Survived.fctr.All.X..rcv.glmnet Survived.fctr.All.X..rcv.glmnet.err
## 8                              <NA>                                  NA
## 139                            <NA>                                  NA
## 201                            <NA>                                  NA
## 263                               Y                                TRUE
## 280                            <NA>                                  NA
## 395                            <NA>                                  NA
##     Survived.fctr.All.X..rcv.glmnet.err.abs
## 8                                        NA
## 139                                      NA
## 201                                      NA
## 263                               0.2333403
## 280                                      NA
## 395                                      NA
##     Survived.fctr.All.X..rcv.glmnet.is.acc
## 8                                       NA
## 139                                     NA
## 201                                     NA
## 263                                  FALSE
## 280                                     NA
## 395                                     NA
##     Survived.fctr.Final..rcv.glmnet.prob Survived.fctr.Final..rcv.glmnet
## 8                              0.2156859                               Y
## 139                            0.2459806                               Y
## 201                            0.2529105                               Y
## 263                            0.2623896                               Y
## 280                            0.2656664                               Y
## 395                            0.4618227                               Y
##     Survived.fctr.Final..rcv.glmnet.err
## 8                                  TRUE
## 139                                TRUE
## 201                                TRUE
## 263                                TRUE
## 280                                TRUE
## 395                                TRUE
##     Survived.fctr.Final..rcv.glmnet.err.abs
## 8                                 0.2156859
## 139                               0.2459806
## 201                               0.2529105
## 263                               0.2623896
## 280                               0.2656664
## 395                               0.4618227
##     Survived.fctr.Final..rcv.glmnet.is.acc
## 8                                    FALSE
## 139                                  FALSE
## 201                                  FALSE
## 263                                  FALSE
## 280                                  FALSE
## 395                                  FALSE
##     Survived.fctr.Final..rcv.glmnet.accurate
## 8                                      FALSE
## 139                                    FALSE
## 201                                    FALSE
## 263                                    FALSE
## 280                                    FALSE
## 395                                    FALSE
##     Survived.fctr.Final..rcv.glmnet.error
## 8                               0.1156859
## 139                             0.1459806
## 201                             0.1529105
## 263                             0.1623896
## 280                             0.1656664
## 395                             0.3618227
##     PassengerId Survived.fctr Survived.fctr.All.X..rcv.glmnet.prob
## 544         111             N                            0.6590845
## 545         546             N                            0.6641134
## 546         175             N                                   NA
## 547         263             N                            0.6645150
## 548         138             N                                   NA
## 549         337             N                            0.6696809
##     Survived.fctr.All.X..rcv.glmnet Survived.fctr.All.X..rcv.glmnet.err
## 544                               Y                                TRUE
## 545                               Y                                TRUE
## 546                            <NA>                                  NA
## 547                               Y                                TRUE
## 548                            <NA>                                  NA
## 549                               Y                                TRUE
##     Survived.fctr.All.X..rcv.glmnet.err.abs
## 544                               0.6590845
## 545                               0.6641134
## 546                                      NA
## 547                               0.6645150
## 548                                      NA
## 549                               0.6696809
##     Survived.fctr.All.X..rcv.glmnet.is.acc
## 544                                  FALSE
## 545                                  FALSE
## 546                                     NA
## 547                                  FALSE
## 548                                     NA
## 549                                  FALSE
##     Survived.fctr.Final..rcv.glmnet.prob Survived.fctr.Final..rcv.glmnet
## 544                            0.6363507                               Y
## 545                            0.6366159                               Y
## 546                            0.6372736                               Y
## 547                            0.6438108                               Y
## 548                            0.6457233                               Y
## 549                            0.6524935                               Y
##     Survived.fctr.Final..rcv.glmnet.err
## 544                                TRUE
## 545                                TRUE
## 546                                TRUE
## 547                                TRUE
## 548                                TRUE
## 549                                TRUE
##     Survived.fctr.Final..rcv.glmnet.err.abs
## 544                               0.6363507
## 545                               0.6366159
## 546                               0.6372736
## 547                               0.6438108
## 548                               0.6457233
## 549                               0.6524935
##     Survived.fctr.Final..rcv.glmnet.is.acc
## 544                                  FALSE
## 545                                  FALSE
## 546                                  FALSE
## 547                                  FALSE
## 548                                  FALSE
## 549                                  FALSE
##     Survived.fctr.Final..rcv.glmnet.accurate
## 544                                    FALSE
## 545                                    FALSE
## 546                                    FALSE
## 547                                    FALSE
## 548                                    FALSE
## 549                                    FALSE
##     Survived.fctr.Final..rcv.glmnet.error
## 544                             0.5363507
## 545                             0.5366159
## 546                             0.5372736
## 547                             0.5438108
## 548                             0.5457233
## 549                             0.5524935

dsp_feats_vctr <- c(NULL)
for(var in grep(".imp", names(glb_feats_df), fixed=TRUE, value=TRUE))
    dsp_feats_vctr <- union(dsp_feats_vctr, 
                            glb_feats_df[!is.na(glb_feats_df[, var]), "id"])

# print(glbObsTrn[glbObsTrn$UniqueID %in% FN_OOB_ids, 
#                     grep(glb_rsp_var, names(glbObsTrn), value=TRUE)])

print(setdiff(names(glbObsTrn), names(glbObsAll)))
## [1] "Survived.fctr.Final..rcv.glmnet.prob"   
## [2] "Survived.fctr.Final..rcv.glmnet"        
## [3] "Survived.fctr.Final..rcv.glmnet.err"    
## [4] "Survived.fctr.Final..rcv.glmnet.err.abs"
## [5] "Survived.fctr.Final..rcv.glmnet.is.acc"
for (col in setdiff(names(glbObsTrn), names(glbObsAll)))
    # Merge or cbind ?
    glbObsAll[glbObsAll$.src == "Train", col] <- glbObsTrn[, col]

print(setdiff(names(glbObsFit), names(glbObsAll)))
## character(0)
print(setdiff(names(glbObsOOB), names(glbObsAll)))
## character(0)
for (col in setdiff(names(glbObsOOB), names(glbObsAll)))
    # Merge or cbind ?
    glbObsAll[glbObsAll$.lcn == "OOB", col] <- glbObsOOB[, col]
    
print(setdiff(names(glbObsNew), names(glbObsAll)))
## character(0)
#glb2Sav(); all.equal(savObsAll, glbObsAll); all.equal(sav_models_lst, glb_models_lst)
#load(file = paste0(glbOut$pfx, "dsk_knitr.RData"))
#cmpCols <- names(glbObsAll)[!grepl("\\.Final\\.", names(glbObsAll))]; all.equal(savObsAll[, cmpCols], glbObsAll[, cmpCols]); all.equal(savObsAll[, "H.P.http"], glbObsAll[, "H.P.http"]); 

replay.petrisim(pn = glb_analytics_pn, 
    replay.trans = (glb_analytics_avl_objs <- c(glb_analytics_avl_objs, 
        "data.training.all.prediction","model.final")), flip_coord = TRUE)
## time trans    "bgn " "fit.data.training.all " "predict.data.new " "end " 
## 0.0000   multiple enabled transitions:  data.training.all data.new model.selected    firing:  data.training.all 
## 1.0000    1   2 1 0 0 
## 1.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction   firing:  data.new 
## 2.0000    2   1 1 1 0 
## 2.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction data.new.prediction   firing:  model.selected 
## 3.0000    3   0 2 1 0 
## 3.0000   multiple enabled transitions:  model.final data.training.all.prediction data.new.prediction     firing:  data.training.all.prediction 
## 4.0000    5   0 1 1 1 
## 4.0000   multiple enabled transitions:  model.final data.training.all.prediction data.new.prediction     firing:  model.final 
## 5.0000    4   0 0 2 1

glb_chunks_df <- myadd_chunk(glb_chunks_df, "predict.data.new", major.inc = TRUE)
##                label step_major step_minor label_minor    bgn    end
## 21 fit.data.training          9          1           1 81.328 86.807
## 22  predict.data.new         10          0           0 86.807     NA
##    elapsed
## 21   5.479
## 22      NA

Step 10.0: predict data new

## Warning in glb_get_predictions(obs_df, mdl_id = glb_fin_mdl_id, rsp_var =
## glb_rsp_var, : Using default probability threshold: 0.1

## Warning in glb_get_predictions(obs_df, mdl_id = glb_fin_mdl_id, rsp_var =
## glb_rsp_var, : Using default probability threshold: 0.1
## Warning: Removed 418 rows containing missing values (geom_point).

## Warning: Removed 418 rows containing missing values (geom_point).

## Warning: Removed 418 rows containing missing values (geom_point).

## Warning: Removed 418 rows containing missing values (geom_point).

## Warning: Removed 418 rows containing missing values (geom_point).

## Warning: Removed 418 rows containing missing values (geom_point).

## Warning: Removed 418 rows containing missing values (geom_point).

## Warning: Removed 418 rows containing missing values (geom_point).

## NULL
## Loading required package: stringr
## Loading required package: tidyr
## 
## Attaching package: 'tidyr'
## The following object is masked from 'package:Matrix':
## 
##     expand
## [1] "OOBobs Survived.fctr.All.X..rcv.glmnet Y: min < min of Train range: 1"
##   PassengerId Survived.fctr.All.X..rcv.glmnet .pos PassengerId.1
## 2           2                               Y    2             2
##                      id        cor.y exclude.as.feat   cor.y.abs
## .pos               .pos -0.005006661           FALSE 0.005006661
## PassengerId PassengerId -0.005006661           FALSE 0.005006661
##             cor.high.X freqRatio percentUnique zeroVar   nzv
## .pos                NA         1           100   FALSE FALSE
## PassengerId         NA         1           100   FALSE FALSE
##             is.cor.y.abs.low interaction.feat shapiro.test.p.value
## .pos                    TRUE               NA         6.308054e-16
## PassengerId             TRUE               NA         6.308054e-16
##             rsp_var_raw id_var rsp_var  max min max.Survived.fctr.N
## .pos              FALSE     NA      NA 1309   1                 886
## PassengerId       FALSE   TRUE      NA 1309   1                 886
##             max.Survived.fctr.Y min.Survived.fctr.N min.Survived.fctr.Y
## .pos                        888                   1                   3
## PassengerId                 888                   1                   3
##             max.Survived.fctr.All.X..rcv.glmnet.Y
## .pos                                          891
## PassengerId                                   891
##             min.Survived.fctr.All.X..rcv.glmnet.Y
## .pos                                            2
## PassengerId                                     2
##             max.Survived.fctr.Final..rcv.glmnet.Y
## .pos                                         1309
## PassengerId                                  1309
##             min.Survived.fctr.Final..rcv.glmnet.Y
## .pos                                          892
## PassengerId                                   892
## [1] "OOBobs Survived.fctr.All.X..rcv.glmnet Y: max > max of Train range: 3"
##     PassengerId Survived.fctr.All.X..rcv.glmnet .pos PassengerId.1
## 889         889                               Y  889           889
## 891         891                               Y  891           891
## 890         890                               Y  890           890
##                      id        cor.y exclude.as.feat   cor.y.abs
## .pos               .pos -0.005006661           FALSE 0.005006661
## PassengerId PassengerId -0.005006661           FALSE 0.005006661
##             cor.high.X freqRatio percentUnique zeroVar   nzv
## .pos                NA         1           100   FALSE FALSE
## PassengerId         NA         1           100   FALSE FALSE
##             is.cor.y.abs.low interaction.feat shapiro.test.p.value
## .pos                    TRUE               NA         6.308054e-16
## PassengerId             TRUE               NA         6.308054e-16
##             rsp_var_raw id_var rsp_var  max min max.Survived.fctr.N
## .pos              FALSE     NA      NA 1309   1                 886
## PassengerId       FALSE   TRUE      NA 1309   1                 886
##             max.Survived.fctr.Y min.Survived.fctr.N min.Survived.fctr.Y
## .pos                        888                   1                   3
## PassengerId                 888                   1                   3
##             max.Survived.fctr.All.X..rcv.glmnet.Y
## .pos                                          891
## PassengerId                                   891
##             min.Survived.fctr.All.X..rcv.glmnet.Y
## .pos                                            2
## PassengerId                                     2
##             max.Survived.fctr.Final..rcv.glmnet.Y
## .pos                                         1309
## PassengerId                                  1309
##             min.Survived.fctr.Final..rcv.glmnet.Y
## .pos                                          892
## PassengerId                                   892
## [1] "OOBobs total range outliers: 4"
## [1] "newobs Survived.fctr.Final..rcv.glmnet Y: max > max of Train range: 418"
##     PassengerId Survived.fctr.Final..rcv.glmnet .pos PassengerId.1
## 892         892                               Y  892           892
## 893         893                               Y  893           893
## 894         894                               Y  894           894
## 895         895                               Y  895           895
## 896         896                               Y  896           896
## 897         897                               Y  897           897
##      PassengerId Survived.fctr.Final..rcv.glmnet .pos PassengerId.1
## 1040        1040                               Y 1040          1040
## 1053        1053                               Y 1053          1053
## 1096        1096                               Y 1096          1096
## 1129        1129                               Y 1129          1129
## 1142        1142                               Y 1142          1142
## 1277        1277                               Y 1277          1277
##      PassengerId Survived.fctr.Final..rcv.glmnet .pos PassengerId.1
## 1304        1304                               Y 1304          1304
## 1305        1305                               Y 1305          1305
## 1306        1306                               Y 1306          1306
## 1307        1307                               Y 1307          1307
## 1308        1308                               Y 1308          1308
## 1309        1309                               Y 1309          1309
##                      id        cor.y exclude.as.feat   cor.y.abs
## .pos               .pos -0.005006661           FALSE 0.005006661
## PassengerId PassengerId -0.005006661           FALSE 0.005006661
##             cor.high.X freqRatio percentUnique zeroVar   nzv
## .pos                NA         1           100   FALSE FALSE
## PassengerId         NA         1           100   FALSE FALSE
##             is.cor.y.abs.low interaction.feat shapiro.test.p.value
## .pos                    TRUE               NA         6.308054e-16
## PassengerId             TRUE               NA         6.308054e-16
##             rsp_var_raw id_var rsp_var  max min max.Survived.fctr.N
## .pos              FALSE     NA      NA 1309   1                 891
## PassengerId       FALSE   TRUE      NA 1309   1                 891
##             max.Survived.fctr.Y min.Survived.fctr.N min.Survived.fctr.Y
## .pos                        890                   1                   2
## PassengerId                 890                   1                   2
##             max.Survived.fctr.All.X..rcv.glmnet.Y
## .pos                                          891
## PassengerId                                   891
##             min.Survived.fctr.All.X..rcv.glmnet.Y
## .pos                                            2
## PassengerId                                     2
##             max.Survived.fctr.Final..rcv.glmnet.Y
## .pos                                         1309
## PassengerId                                  1309
##             min.Survived.fctr.Final..rcv.glmnet.Y
## .pos                                          892
## PassengerId                                   892
## [1] "newobs total range outliers: 418"
## [1] TRUE
## [1] 0.1
## [1] "glb_sel_mdl_id: All.X##rcv#glmnet"
## [1] "glb_fin_mdl_id: Final##rcv#glmnet"
## [1] "Cross Validation issues:"
##        MFO###myMFO_classfr  Random###myrandom_classfr 
##                          0                          0 
## Max.cor.Y.rcv.1X1###glmnet 
##                          0
##                            max.Accuracy.OOB max.AUCROCR.OOB
## Max.cor.Y.rcv.1X1###glmnet        0.4120735       0.6326125
## Low.cor.X##rcv#glmnet             0.3805774       0.6326125
## All.X##rcv#glmnet                 0.3805774       0.6326125
## All.X##rcv#glm                    0.3805774       0.6265634
## Max.cor.Y##rcv#rpart              0.3805774       0.6225015
## MFO###myMFO_classfr               0.3805774       0.5000000
## Random###myrandom_classfr         0.3805774       0.4456750
## Final##rcv#glmnet                        NA              NA
##                            max.AUCpROC.OOB max.Accuracy.fit
## Max.cor.Y.rcv.1X1###glmnet       0.6118498        0.7078431
## Low.cor.X##rcv#glmnet            0.6212011        0.7105259
## All.X##rcv#glmnet                0.6212011        0.7105259
## All.X##rcv#glm                   0.6091905        0.7046551
## Max.cor.Y##rcv#rpart             0.6137639        0.7078962
## MFO###myMFO_classfr              0.5000000        0.3862745
## Random###myrandom_classfr        0.4867621        0.3862745
## Final##rcv#glmnet                       NA        0.6887392
##                            opt.prob.threshold.fit opt.prob.threshold.OOB
## Max.cor.Y.rcv.1X1###glmnet                    0.4                    0.2
## Low.cor.X##rcv#glmnet                         0.4                    0.1
## All.X##rcv#glmnet                             0.4                    0.1
## All.X##rcv#glm                                0.4                    0.1
## Max.cor.Y##rcv#rpart                          0.3                    0.2
## MFO###myMFO_classfr                           0.3                    0.3
## Random###myrandom_classfr                     0.3                    0.3
## Final##rcv#glmnet                             0.4                     NA
## [1] "All.X##rcv#glmnet OOB confusion matrix & accuracy: "
##          Prediction
## Reference   N   Y
##         N   0 236
##         Y   0 145
##   err.abs.fit.sum err.abs.OOB.sum err.abs.trn.sum err.abs.new.sum
## 2        47.72973        43.79759        90.70589              NA
## 1        57.64010        42.06919       102.26621              NA
## 3        97.24814        79.20811       182.93226              NA
##   .freqRatio.Fit .freqRatio.OOB .freqRatio.Tst .n.Fit .n.New.Y .n.OOB
## 2      0.1882353      0.2309711      0.2224880     96       93     88
## 1      0.2549020      0.2257218      0.2559809    130      107     86
## 3      0.5568627      0.5433071      0.5215311    284      218    207
##   .n.Trn.N .n.Trn.Y .n.Tst .n.fit .n.new .n.trn err.abs.OOB.mean
## 2       97       87     93     96     93    184        0.4976999
## 1       80      136    107    130    107    216        0.4891767
## 3      372      119    218    284    218    491        0.3826479
##   err.abs.fit.mean err.abs.new.mean err.abs.trn.mean
## 2        0.4971847               NA        0.4929668
## 1        0.4433854               NA        0.4734547
## 3        0.3424230               NA        0.3725708
##  err.abs.fit.sum  err.abs.OOB.sum  err.abs.trn.sum  err.abs.new.sum 
##       202.617974       165.074900       375.904355               NA 
##   .freqRatio.Fit   .freqRatio.OOB   .freqRatio.Tst           .n.Fit 
##         1.000000         1.000000         1.000000       510.000000 
##         .n.New.Y           .n.OOB         .n.Trn.N         .n.Trn.Y 
##       418.000000       381.000000       549.000000       342.000000 
##           .n.Tst           .n.fit           .n.new           .n.trn 
##       418.000000       510.000000       418.000000       891.000000 
## err.abs.OOB.mean err.abs.fit.mean err.abs.new.mean err.abs.trn.mean 
##         1.369524         1.282993               NA         1.338992
## [1] "Features Importance for selected models:"
##              All.X..rcv.glmnet.imp Final..rcv.glmnet.imp
## Pclass.fctr3              100.0000             100.00000
## Pclass.fctr2               30.8228              32.05381
## [1] "glbObsNew prediction stats:"
## 
##   N   Y 
##   0 418
##                   label step_major step_minor label_minor    bgn    end
## 22     predict.data.new         10          0           0 86.807 95.698
## 23 display.session.info         11          0           0 95.699     NA
##    elapsed
## 22   8.891
## 23      NA

Null Hypothesis (\(\sf{H_{0}}\)): mpg is not impacted by am_fctr.
The variance by am_fctr appears to be independent. #{r q1, cache=FALSE} # print(t.test(subset(cars_df, am_fctr == "automatic")$mpg, # subset(cars_df, am_fctr == "manual")$mpg, # var.equal=FALSE)$conf) # We reject the null hypothesis i.e. we have evidence to conclude that am_fctr impacts mpg (95% confidence). Manual transmission is better for miles per gallon versus automatic transmission.

##                        label step_major step_minor label_minor    bgn
## 16                fit.models          8          0           0 27.978
## 17                fit.models          8          1           1 48.226
## 18                fit.models          8          2           2 62.676
## 22          predict.data.new         10          0           0 86.807
## 2               inspect.data          2          0           0 15.492
## 1                import.data          1          0           0  9.263
## 20         fit.data.training          9          0           0 75.789
## 21         fit.data.training          9          1           1 81.328
## 19                fit.models          8          3           3 72.181
## 3                 scrub.data          2          1           1 22.709
## 15           select.features          7          0           0 26.504
## 11      extract.features.end          3          6           6 24.789
## 14   partition.data.training          6          0           0 26.043
## 12       manage.missing.data          4          0           0 25.728
## 10   extract.features.string          3          5           5 24.732
## 7     extract.features.image          3          2           2 24.583
## 9      extract.features.text          3          4           4 24.674
## 13              cluster.data          5          0           0 25.996
## 4             transform.data          2          2           2 24.485
## 8     extract.features.price          3          3           3 24.637
## 6  extract.features.datetime          3          1           1 24.547
## 5           extract.features          3          0           0 24.526
##       end elapsed duration
## 16 48.225  20.247   20.247
## 17 62.675  14.449   14.449
## 18 72.180   9.504    9.504
## 22 95.698   8.891    8.891
## 2  22.708   7.216    7.216
## 1  15.491   6.228    6.228
## 20 81.327   5.538    5.538
## 21 86.807   5.479    5.479
## 19 75.789   3.608    3.608
## 3  24.484   1.776    1.775
## 15 27.978   1.474    1.474
## 11 25.728   0.939    0.939
## 14 26.504   0.461    0.461
## 12 25.995   0.267    0.267
## 10 24.788   0.056    0.056
## 7  24.637   0.054    0.054
## 9  24.727   0.053    0.053
## 13 26.043   0.047    0.047
## 4  24.525   0.041    0.040
## 8  24.674   0.037    0.037
## 6  24.582   0.035    0.035
## 5  24.546   0.020    0.020
## [1] "Total Elapsed Time: 95.698 secs"

##                            label step_major step_minor      label_minor
## 4 fit.models_0_Max.cor.Y.rcv.*X*          1          3           glmnet
## 5         fit.models_0_Low.cor.X          1          4           glmnet
## 2               fit.models_0_MFO          1          1    myMFO_classfr
## 3            fit.models_0_Random          1          2 myrandom_classfr
## 1               fit.models_0_bgn          1          0            setup
##      bgn    end elapsed duration
## 4 34.014 42.581   8.567    8.567
## 5 42.582 48.211   5.629    5.629
## 2 28.491 31.448   2.957    2.957
## 3 31.448 34.014   2.566    2.566
## 1 28.456 28.491   0.035    0.035
## [1] "Total Elapsed Time: 48.211 secs"